Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript smooth scroll on click

I'm using this link:

<a class="" onclick="location.href='#top'" href="superContent">superContent</a>

It does two things at once:

  1. Jumps user to top of the page
  2. Performs this other (unrelated) ajax load function

Everything works great, except I'm trying to figure out how to get it to scroll to the top more smoothly. I've tried adding .scroll to attach it to my jquery scrollTo plugin, but nothing happens, which probably has something to do with the fact that I'm using javascript onclick, while the href attribute does something else entirely.

Is there a way to attach animated smooth-scrolling to onclick="location.href='#top'" ?

like image 586
user1691389 Avatar asked Oct 22 '12 17:10

user1691389


People also ask

How do I make my anchor link scroll smoother?

You can use window. scroll() with behavior: smooth and top set to the anchor tag's offset top which ensures that the anchor tag will be at the top of the viewport.

How do I make my scrollTop smoother?

Now you can use just window. scrollTo({ top: 0, behavior: 'smooth' }) to get the page scrolled with a smooth effect.

How do you navigate to another page with a smooth scroll on a specific ID?

Modern Browsers detect the hash in the url and then automatically open that part. So, if you want to scroll smoothly to that part instead, you first need to reset the scroll position to 0 and then add smooth scrolling. // direct browser to top right away if (window. location.


1 Answers

Try this, it animates the scrollTop() function.

Set link's id:

<a id="link">link</a>

jquery to scroll:

$('#link').click(function(e){
  var $target = $('html,body');
  $target.animate({scrollTop: $target.height()}, 500);
});
like image 100
PRNDL Development Studios Avatar answered Oct 09 '22 11:10

PRNDL Development Studios