I need to scroll through a page using anchor tag
.
Right now I'm doing:
<a href="#div1">Link1</a> <div id='div1'>link1 points me!!</div>
This works fine when I clicked on Link1, the page scrolls to the div with id "div1".
The point is, I do not want to change my URL which takes #div
as suffix once I clicked on Link1
.
I tried with anchor href as
void(0);
and
location.hash='#div1'; return false; e.preventdefault;
How to avoid changing the URL?
To achieve a smooth scrolling effect for anchor links, add a scroll modifier—block T178 from the "Other" category to the bottom of your page. Now, when you click an anchor link, the transition will be smoothly animated.
The easiest way to to make the browser to scroll the page to a given anchor is to add *{scroll-behavior: smooth;} in your style. css file and in your HTML navigation use #NameOfTheSection .
Yes, it is valid to use the anchor tag without a href attribute. If the a element has no href attribute, then the element represents a placeholder for where a link might otherwise have been placed, if it had been relevant, consisting of just the element's contents.
Take this answer from Jeff Hines using jQuery's animate:
function goToByScroll(id){ $('html,body').animate({scrollTop: $("#"+id).offset().top},'slow'); }
If you're using jQuery don't forget to add the library to your project.
Edit: Also, make sure that you still "return false;" in the click handler for the link, otherwise it'll still add the "#div1" to your URL (thanks @niaccurshi)
scrollIntoView
did the best job when all other methods failed!
document.getElementById('top').scrollIntoView(true);
Where 'top'
is the id of the html tag you want to go.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With