mayank mayank - 6 months ago 104
Javascript Question

scroll with anchor without # in URL

I need to scroll through page using anchor tag.

right now i m doing it like

<a href="#div1">Link1</a>

<div id='div1'>link1 points me!!</div>


This works fine when i clicked on Link1, Page scroll to div has id "div1".

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;


none of them worked for me.

please help if any one have more option to avoid change in URL

Thanks in advance

Answer

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)

Comments