How to navigate to a section in the page without using id? - javascript

I know you can navigate to a section in the page using anchor tags, but doing this adds unwanted keywords to the URL.
So if the original URL was www.xyz.com, clicking on an anchor tag abc would change the URL to www.xyz.com/#abc. I do not want the URL to change since this every time you click on "back", it just goes to the previous section that the URL held previously. Is there any way to stop this from happening? Maybe reroute the back button to leave the website or something?

Have you tried using JavaScript? Use scrollintoview function.
Here's an example:
<a onclick="scrollthere()">go to the content<\a>
<h1 id="stophere">This is content</h1>
<script>
function scrollthere(){
var element = document.querySelector("#stophere");
element.scrollIntoView();
}
</script>
Something like that. Onclick is an event. And in brackets we write function that we want to execute when clicked on it. In our case it's scrollthere which scrolls to our h1 element that has is "stophere". It will scroll untill our element won't get into view. You could read more about it here . Good luck with your website. I'm making website as well :).

My solution is to use JS instead of using <a> behavior.
for example
document.querySelectorAll("a").forEach((item, idx) => {
item.addEventListener("click", (e) => {
e.preventDefault();
const hash = e.target.hash;
window.scrollTo({
top: document.querySelector(hash).offsetTop,
behavior: "smooth"
});
});
});
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.section {
width: 100%;
height: 100vh;
}
.sec-1 {
background-color: salmon;
}
.sec-2 {
background-color: teal;
}
Section 1
Section 2
<div id="sec-1" class="section sec-1"></div>
<div id="sec-2" class="section sec-2"></div>
In my case, I use the scrollTo() property.
Hope this might help you.

You can set your href attribute to empty string.
abc

Related

How to make an image hidden then appear at a certain time

I am not really a coder but I'm trying to run some basic javascript on a landing page builder (Samcart) so that an image will be hidden then appear after the user has been onpage for a certain length of time.
I have tried a few things. So far, I was able to bring in the image from imgur successfully. So I can display it fine. I'm just struggling to know what javascript code to use.
I found some javascript code that should enable this for me:
<script>
$("div").hide();
setTimeout(function(){
$("div").show();
},3000);
</script>
This is the code I created on the page to pull the image from imgur:
<div class="valuestack">
<img src="https://i.imgur.com/TrGitqf.png" width="60000" height="1300">
</div>
I honestly don't really know what I'm doing and need some clarification.
Thank you in advance,
Nathan
Hey #Nathan here is a JavaScript solution to your problem.
You are using setTimeout() function which expects a function to be passed to it.
The syntax of the above function is as below -
setTimeout(function(){
document.getElementById('valuestack').style.visibility = 'visible';
}, 2000);
Additionally, instead of hiding it through JavaScript/JQuery, you might consider just applying a CSS style to handle it being hidden by default (i.e. display: none) and then simply showing it within the body of your setTimeout() function call.
function showImage() {
if (document.getElementById("valuestack") != null) {
document.getElementById('valuestack').style.visibility = 'hidden';
setTimeout(function() {
document.getElementById('valuestack').style.visibility = 'visible';
}, 2000);
}
}
showImage();
.v-image {
width: 50px;
height: 50px;
}
.v-stack {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
body {
background-color: black;
}
<body>
<div id="valuestack" class="v-image v-stack">
<img src="https://i.imgur.com/TrGitqf.png" width="600" height="1300" >
</div>
</body>
The code you posted uses jQuery. You will need to include jQuery on the page for it to work.
Also, this code will hide and show all <div> elements on your page. You'll probably want to change the code to target div.valuestack instead.
There are two things here
You need to include JQuery as below. (there are more methods to include, this is just one way)<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
The method that you have written in script tag is never called. So this small code must be called when your landing page is load.
<script>
window.onload = function() {
$(".valuestack").hide();
setTimeout(function() {
$(".valuestack").show();
}, 3000);
}
</script>

Add a class to an Anchor using a specific smoot-scroll library

I've recently installed the smooth-scroll library from cferdinandi and the smooth-scroll feature works like a charm.
The anchors added to my text using a CMS where looking like this:
<span id="authentication" class="ancre"></span>
The ID being different each time, regarding what I'm talking about in my text. And it works fine.
My problem is that the smooth-scroll library seems to remove the class when it runs, therefore my class='ancre' does not show when the anchor is called. Class being:
.ancre:target{
background-color: #131b24;
color: white;
}
So what I did it that I removed the "target" parameter of my class and added a function to my JS file to add the class after the smooth-scroll is run. It looks like this:
CSS in css/app.css
.ancre{
background-color: #131b24;
color: white;
}
JS in js/app.js
after: function () {
var className = 'ancre';
document.querySelector('.' + className).classList.remove(className);
document.getElementById(anchor.id).classList.add(className);
}
But it does not work and I just couldn't figure out why.
You can try it by pressing the buttons "2-step authentication" and/or "Mobile" on this page.
I'm not a coder, more a designer and I would be happy to get some help here.
Thank you all for your help,
Best,
Kwint
You can use the scrollIntoView javascript function without the need for a library.
https://codepen.io/gezzasa/pen/gzXPbJ/
first I had to set the containers to position: relative; and then set the anchor to position: absolute; top: 0;. with the option on the JS set to block : 'center' it will now only scroll till the anchor is in the middle of the screen.
var smoothScroll = function(e, me) is the function I declared and gets fired on the onclick of the a tag. There are different ways to run the function but this is easy enought. I passed in event on the onclick for the event(event thats fired when you click) and this to tell the script what I clicked on.
e.preventDefault() will prevent the a tag from firing its default function which will reload the page with the href provided. in this case it will append an ID without that script.
document.querySelector(me.getAttribute('href')) will get the ID that it needs to scroll to and then the scrollIntoView function will scroll according to the options that you give it.
Hope I explained it well...I don't have a ton of experience explaining JS.;

HTML Divs show/hide issue

Hi friends I have issue with divs.
I have a link show/hide dive on my page on clicking which i have to show or hide specific divs.
I am successful with doing it.
But my issue is that whenever I click on that link div is get hide or shown but page get directly on the top & I have to scroll to down again.
I don't want to scroll this and don't want to get to top.
Please help me out with this.
Thank You in advance.
Update:
Friend I got the answer from one of my friend.
Actually I was using
Because of href="#" URL get changed and page got to top every time I click on that link.
Are you trying to do this?
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="utf-8">
</head>
<body>
<div id="wrapper">
<div id="container">
</div><!-- end of #container div -->
<a id="showdiv">Show the div</a>|<a id="hideDiv">Hide the div</a>|<a id="toggle">Toggle</a>
</div><!-- end of #wrapper div -->
</body>
</html>
Here's the css:
#container {
width: 300px;
height: 300px;
background: red;
margin-bottom: 20px;
}
#wrapper {
margin: 40px auto;
width: 400px;
}
And here's the jquery
$(function() {// When document is ready, run this...
//Get hold of the link with the id #showdiv and do something when you click it
$("#showdiv").click(function() {
// Grab the div with the id #container and show it
// Alert me when you're done
$("#container").show(2000, function() {
alert("I'm done showing");
});
});
//Get hold of the link with the id #hideDiv and do something when you click it
$("#hideDiv").click(function() {
// Grab the div with the id #container and hide it
// Alert me when you're done
$("#container").hide(2000, function() {
alert("I'm done hiding");
});
});
// Toggle - This is like a On/Off Switch
//Get hold of the link with the id #toggle and do something when you click it
$("#toggle").click(function() {
// Grab the div with the id #container and show if hidden / hide if shown
$("#container").toggle(2000);
});
});
Of course you'd have to link to a copy of jQuery before using the script above.
Here's a link to a demo: http://jsfiddle.net/tonystark/HhNBA/
Assuming you have a link
Inline (not recommended but likely what you have)
<script>
function showhide(id) {
var elem = document.getElementById(id);
elem.style.display=elem.style.display=="none"?"block":"none";
return false; // MANDATORY
}
</script>
Toggle
<div id="someId">Show or hide me when you click a link</div>
You have to cancel the default behavior of the onclick handler of your link. For doing so, don't use return false in your click handler, but rather use event.preventDefault():
HTML:
hide me
<div id="#targetdiv">blah</div>
Javascript:
document.querySelector('a.foo').onclick = function(event) {
try {
document.querySelector(this.getAttribute('href')).style.display = 'none';
} catch (e) {
console.error("couldn't find element to hide");
}
event.preventDefault();
}
JQuery:
$('a.foo').click(function(event) {
try {
$($(this).attr('href')).hide();
} catch (e) {
console.error("couldn't find element to hide");
}
event.preventDefault();
})
More informations:
http://www.quirksmode.org/js/events_early.html
http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/
It happens because your link is pointing to something like #foo or just #, whereas it should not have a href (or have an empty one)...
remove the href attribute and apply a text-decoration style
<a style="text-decoration: underline;" title="click me"></a>
that'd seem to make more sense than applying an href you dont want, to block its normal operation later. an alternative for graceful degradation would be to use the href to point to the shown/hidden div, displaying normally by default and having javascript hide it where javascript is available.
"Change your anchor (link) to a span so that it doesn't have that behaviour. Then, style it using css so it looks how you want it to look."
i often use that techique. i.e., use a span or div with an onclick, styled with text-decoration: underline, cursor: pointer and possibly display: inline if you decide on a div. one caveat is that in IE6, css hover won't work on anything other than an anchor. that's easily fixed with javascript.
you could probably remove the href attribute completely. anchors have advantages as above (cross-browser :hover styles) and allow for a title attribute for tool tips etc.
you probaby have a # in href attribute like href=# please remove hash and instead of that write href='javascript:void(null);'

How to prevent users from clicking multiple times on a linked image?

I have a page with a linked image, where the link takes a bit of time to load. Therefore, users tend to click multiple times on it. This occasionally causes errors to crop up in the code. How do I prevent users from clicking on the link more than once?
In an attempt to remedy this, I changed the link to an onClick event and then in the function I used the code:
$('#myImageId').unbind('click');
window.location.href = "myLink";
However, that doesn't seem to be helping. Also, I'd prefer to keep it a simple linked image instead of using javascript.
Once solution is to add a class to the element that is used as a flag to determine of the code should run.
Here's an example: http://jsfiddle.net/qLhr8/
$('#myImageId').click(function() {
var $th = $(this);
if( !$th.hasClass( "pending" ) ) {
// Add the "pending" class, so subsequent clicks will not
// run the code inside this if()
$th.addClass( "pending" );
window.location.href = "myLink";
// you could do a setTimeout to remove the class
// if the new page never loads
}
});
With the added class, you can also change the look of the image (lower its opacity perhaps) to indicate that it shouldn't be clicked again.
.pending {
opacity: .4;
filter:alpha(opacity:40);
cursor: wait;
}
<img src="..." id="myImageId">
$('#myImageId').bind('click', function() {
$(this).unbind('click');
/* do long time task....
});
if your image is wrapped by a link the code will be
<img src="..." id="myImageId">
$('#myImageId').parent().bind('click', function(evt) {
$(this).unbind('click');
/* do long time task....
evt.preventDefault();
});
A hacky CSS solution that might/might not work: create another image element, without the link and make it a sibling to the link, like this:
<div>
<img src="my_img.png" id="img_link" alt="GO" />
<img src="my_img.png" id="img_nolink" alt="GO" />
</div>
Now apply this CSS:
#img_nolink { display: none; position: relative; top: -200px; /* Height of the image */ }
#link:active + #img_nolink { display: block; }
This should show the non-link image when the link is clicked (theoretically).

How to disable user's input while loading page with jQuery?

I have a heavy-jquerized page with some links, various user inputs and such.
I use jquery, with actions defined in a
$(document).ready( function() {
....
} );
block.
But while the page is loading (or, even worse - reloading), and a user clicks a link, the href action from it is triggered, as the javascript isn't loaded / active yet.
I wanted to block it somehow. One way that came to my mind is to put a transparent div over whole document, that would receive the click events instead of the layer below it. Then, in my .ready function in javascript, I could hide that div making it possible to use the page.
Is it a good practice? Or should I try some different approach?
Another option is to use the jQuery BlockUI plugin (which probably usew the same or similar idea behind the scenes).
If you don't want your links to act like links (ie their href is never meant to followed), why make them links in the first place? You'd be better served by making your clickable elements a div or span (something without a default action), and attaching the click handler as per normal.
I'd really advise against blocking the ui with a div - it seems the entirely wrong approach, making the page non-functional to someone with JS disabled, as well as blocking other common tasks like copying text.
In light of the clarification, to block the UI only if JS is enabled, but not yet loaded, I'd suggest the following.
HTML (first thing after body):
<script type="text/javascript">document.write('<div id="UIBlocker">Please wait while we load...</div>')</script>
CSS:
#UIBlocker
{
position: fixed; /* or absolute, for IE6 */
top: 0;
bottom: 0;
left: 0;
right: 0;
}
Or, if you prefer not to use document.write, leave the UIBlocker div as straight HTML at the top of body, but have the following in head
HTML:
<noscript>
<style type="text/css">
#UIBlocker { display: none !important; }
</style>
</noscript>
This will ensure it does not block for non-JS enabled browsers
A transparent div could work, assuming it’s positioned above everything. (I’m never quite clear how visible an element has to be to receive click events.)
You might want to make the div visible though; it could be equally confusing for visitors if they can see everything on the page, but not click it.
You’ll probably need to use JavaScript to make the div as tall as the page though.
The overlay DIV should work. Another option would be to place all the content inside a hidden container visibility: hidden then toggle to visible as the last $(document).ready statement.
As you said it yourself javascript isn't loaded yet. Maybe the css isn't loaded either.
so something with visual element will not work i think. IF you want to do some with the viaual elements (css) you have to hardcode it in the html node <tagname style="blabla">
You could possibly add the href behavious in a later stadium when the js is loaded.
What you get is a <span> with a title and this should set the behaviour or something. I used a title, but can be a different attribute.
This doesn't use any jquery, only for loading
$(document).reade(function () {
relNoFollow();
});
function relNoFollow() {
var FakeLinks = document.getElementsByTagName('span');
if( FakeLinks.length > 0 ) {
for( var i = 0; i < FakeLinks.length; i++ ) {
if( FakeLinks[i].title.indexOf( 'http://' ) != -1 ) {
FakeLinks[i].onmouseout = fakelinkMouseOut;
FakeLinks[i].onmouseover = fakelinkMouseOver;
FakeLinks[i].onclick = fakelinkClick;
}
}
}
}
function fakelinkMouseOver() {
this.className = 'fakelink-hover';
}
function fakelinkMouseOut() {
this.className = 'fakelink';
}
function fakelinkClick() {
window.location.href = this.title;
}

Categories

Resources