35

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?

Alireza
  • 100,211
  • 27
  • 269
  • 172
Mayank
  • 934
  • 1
  • 17
  • 37

8 Answers8

51

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.

Alireza
  • 100,211
  • 27
  • 269
  • 172
stallingOne
  • 3,633
  • 3
  • 41
  • 63
  • Thanks a lot dear! – gaurav414u Jun 12 '18 at 11:35
  • Upvote even though this didn't work for me for some reason last time I tried. – Marc.2377 Feb 04 '19 at 13:39
  • 2
    This is a better solution than the accepted one because when I used the accepted one, it doesn't take into account any margins above or below the position being scrolled to. As a result, part of the text is cut off when the scrolling is done. – Johann Mar 19 '19 at 08:48
  • Though I like this answer, it fails to also bring focus to where you scroll. For example if you have a "Skip to main content" link for accessible users and you want to scroll to the main content, using this will not move the focus to the main content area. – maxshuty Aug 18 '20 at 16:36
  • ```scrollIntoViewOptions``` don't work in Safari though. – Tanushree Jun 20 '21 at 07:34
47

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)

henser
  • 3,307
  • 2
  • 36
  • 47
  • 7
    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 – niaccurshi Mar 05 '13 at 11:51
  • This works well. Spent a bunch of time on the old # anchor tags but they seem to get 'broken' when there is a bunch of scripting. – pat capozzi Feb 20 '17 at 18:55
9

Make your life easier, try the following and let me know if there is anything else ;-)

<div>top</div>
<div style="height: 800px;">&nbsp;</div>
<div><a href="javascript:void(0);" onclick="window.scroll(0,1);">click here</a></div>

FYI: You only need to play around with one/single line href="javascript:void(0);" onclick="window.scroll(0,1);" and it works for you.

Have a good day!

Alireza
  • 100,211
  • 27
  • 269
  • 172
mknayab
  • 302
  • 2
  • 4
  • 10
4

Only Add this code into jquery on document ready

Ref : http://css-tricks.com/snippets/jquery/smooth-scrolling/

$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^/ / , '') == this.pathname.replace(/^/ / , '') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});
Jonatas Walker
  • 13,583
  • 5
  • 53
  • 82
Saygın Karahan
  • 167
  • 1
  • 9
2

Add smooth scroll to any item click including anchor, button etc without adding div id to URL :)

Info: scrollIntoViewOptions(Optional) { behavior: "auto" | "instant" | "smooth", block: "start" | "end", }

function scrollSmoothTo(elementId) {
  var element = document.getElementById(elementId);
  element.scrollIntoView({
    block: 'start',
    behavior: 'smooth'
  });
}
#userdiv {
  margin-top: 200px;
  width: 200px;
  height: 400px;
  border: 1px solid red;
}
<button onclick="scrollSmoothTo('userdiv')">
  Scroll to userdiv
</button>

<div id="userdiv">
  Lorem ipsum this is a random text
</div>

DEMO

Reference: https://developer.mozilla.org/en/docs/Web/API/Element/scrollIntoView

Manoj Selvin
  • 2,247
  • 24
  • 20
1

Riffing off Henser's answer, I have a case where the window.location.hash is already set, and the user then scrolls back to the top of the page (where the hash link is).

Since the hash is already set, you can re-locate on clicking that link by:

$(window).scrollTop($('a[name='+id+']').offset().top);
Sreenikethan I
  • 319
  • 5
  • 17
dhc
  • 647
  • 8
  • 17
1

I'm know I'm 4 years late, but you guys can try this.

HTML:

<a href="#div1">Link1</a>
<!-- you can put <br />'s here to see effect -->
<div id='div1'>link1 points me!!</div>
<!-- <br />'s here, too, to see effect -->

JavaScript/jQuery

$(document).ready(function(){
    $('a').on('click', function(event) {
        event.preventDefault();
        var hash = this.hash;
        $('html, body').animate({scrollTop: $(hash).offset().top}, 900);
    });
})
edsonski
  • 63
  • 1
  • 2
  • 8
  • 1
    This is really bad. As written when you click **ANY** anchor tag, you will initialize this function. You should target a specific ID. Also, your solution does not work. – JGallardo Sep 18 '17 at 23:33
  • it works well you just need to define the class instead of universal "a" tag – Yasir Khan Aug 29 '18 at 23:08
0
document.getElementById('top').scrollIntoView(true);

should work for all browser, tested!

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103