medium
medium

Reputation: 4236

JQuery scroll to top of page

Is there a way to programmatically scroll to the top of a page with jQuery? I am currently trying to do this with the following code but it is not working. I am using Firefox currently,

$(window).scrollTop($(document).height());

Upvotes: 34

Views: 51306

Answers (4)

subindas pm
subindas pm

Reputation: 2784

$('a[href^="#"]').on('click', function(event) {
  var target = $(this.getAttribute('href'));
   if( target.length ) {
      event.preventDefault();
      $('html, body').stop().animate({
        scrollTop: target.offset().top
      }, 1000);
   }
});

Add this to the HTML

<div id="top"></div>
<a href="#top">Click to scroll up</a>

Upvotes: 0

luigi7up
luigi7up

Reputation: 5962

No need for jQuery here. Use native:

window.scrollTo(x-coordinate, y-coordinate);

Note that this has no control over animate part (duration etc.) that jQuery provides

Upvotes: 3

Banjer
Banjer

Reputation: 8320

Just adding a snippet to Nick's nice answer. This shows your "scroll to top" element only after the user has scrolled down the page some, i.e. Pinterest-style.

  $("#scroll_to_top_button").hide(); // hide on page load

  $(window).bind('scroll', function(){
    if($(this).scrollTop() > 200) { // show after 200 px of user scrolling
      $("#scroll_to_top").slideDown("fast");
   }
  });

Upvotes: 3

Nick Craver
Nick Craver

Reputation: 630549

Try this:

$('html, body').animate({scrollTop: '0px'}, 300);

You can do this with 0 instead of 300 to be instant, but this gives a quick auto-scroll effect.

Upvotes: 77

Related Questions