Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll with anchor without # in URL

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?

like image 848
Mayank Avatar asked Mar 05 '13 11:03

Mayank


People also ask

How do I smooth scroll to anchor?

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.

How do you make a scroll anchor?

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 .

Can you have an anchor tag without href?

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.


2 Answers

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)

like image 185
henser Avatar answered Oct 02 '22 04:10

henser


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.

like image 37
stallingOne Avatar answered Oct 02 '22 04:10

stallingOne