jQuery .scrollTop(); + animation

JqueryJquery AnimateScrolltop

Jquery Problem Overview


I set the page to scroll to top when a button is clicked. But first I used an if statement to see if the top of the page was not set to 0. Then if it's not 0 I animate the page to scroll to the top.

var body = $("body");
var top = body.scrollTop() // Get position of the body
 
if(top!=0)
{
  body.animate({scrollTop:0}, '500');
}

The tricky part now is animating something AFTER the page has scrolled to the top. So my next thought is, find out what the page position is. So I used console log to find out.

console.log(top);  // the result was 365

This gave me a result of 365, I'm guessing that is the position number I was at just before scrolling to the top.

My question is how do I set the position to be 0, so that I can add another animation that runs once the page is at 0?

Thanks!

Jquery Solutions


Solution 1 - Jquery

To do this, you can set a callback function for the animate command which will execute after the scroll animation has finished.

For example:

var body = $("html, body");
body.stop().animate({scrollTop:0}, 500, 'swing', function() { 
   alert("Finished animating");
});

Where that alert code is, you can execute more javascript to add in further animation.

Also, the 'swing' is there to set the easing. Check out http://api.jquery.com/animate/ for more info.

Solution 2 - Jquery

Try this code:

$('.Classname').click(function(){
    $("html, body").animate({ scrollTop: 0 }, 600);
    return false;
});

Solution 3 - Jquery

Use this:

$('a[href^="#"]').on('click', function(event) {

    var target = $( $(this).attr('href') );

    if( target.length ) {
        event.preventDefault();
        $('html, body').animate({
            scrollTop: target.offset().top
        }, 500);
    }

});

Solution 4 - Jquery

for this you can use callback method

body.animate({
      scrollTop:0
    }, 500, 
    function(){} // callback method use this space how you like
);

Solution 5 - Jquery

Try this instead:

var body = $("body, html");
var top = body.scrollTop() // Get position of the body
if(top!=0)
{
       body.animate({scrollTop :0}, 500,function(){
         //DO SOMETHING AFTER SCROLL ANIMATION COMPLETED
          alert('Hello');
      });
}

Solution 6 - Jquery

Simple solution:

scrolling to any element by ID or NAME:

SmoothScrollTo("#elementId", 1000);

code:

function SmoothScrollTo(id_or_Name, timelength){
	var timelength = timelength || 1000;
	$('html, body').animate({
		scrollTop: $(id_or_Name).offset().top-70
	}, timelength, function(){
		window.location.hash = id_or_Name;
	});
}

Solution 7 - Jquery

Code with click function()

    var body = $('html, body');

    $('.toTop').click(function(e){
    	e.preventDefault();
    	body.animate({scrollTop:0}, 500, 'swing');

});	

.toTop = class of clicked element maybe img or a

Solution 8 - Jquery

jQuery("html,body").animate({scrollTop: jQuery("#your-elemm-id-where you want to scroll").offset().top-<some-number>}, 500, 'swing', function() { 
       alert("Finished animating");
    });

Solution 9 - Jquery

you can use both CSS class or HTML id, for keeping it symmetric I always use CSS class for example

<a class="btn btn-full js--scroll-to-plans" href="#">I’m hungry</a> 
|
|
|
<section class="section-plans js--section-plans clearfix">

$(document).ready(function () {
    $('.js--scroll-to-plans').click(function () {
        $('body,html').animate({
            scrollTop: $('.js--section-plans').offset().top
        }, 1000);
        return false;})
});

Solution 10 - Jquery

you must see this

$(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;
                }
            }
        });
    });

or try them

$(function () {$('a').click(function () {
$('body,html').animate({
    scrollTop: 0
}, 600);
return false;});});

Solution 11 - Jquery

$("body").stop().animate({
        scrollTop: 0
    }, 500, 'swing', function () {
        console.log(confirm('Like This'))
    }
);

Solution 12 - Jquery

Hello everyone I was facing a similar issue and this worked fine for me:

jQuery(document).on('click', 'element', function() {
  let posTop = jQuery(target).offset().top;
  console.log(posTop);
  $('html, body').animate({scrollTop: posTop}, 1, function() {
    posTop = jQuery(target).offset().top;

    $('html, body').animate({scrollTop: posTop}, 'slow');
  });
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJuan Di DiegoView Question on Stackoverflow
Solution 1 - JqueryTLSView Answer on Stackoverflow
Solution 2 - JqueryShaileshView Answer on Stackoverflow
Solution 3 - JqueryBeepView Answer on Stackoverflow
Solution 4 - JqueryThe MechanicView Answer on Stackoverflow
Solution 5 - JqueryKishan PatelView Answer on Stackoverflow
Solution 6 - JqueryT.ToduaView Answer on Stackoverflow
Solution 7 - JqueryScorbyView Answer on Stackoverflow
Solution 8 - JqueryJunaidView Answer on Stackoverflow
Solution 9 - JqueryRafiqView Answer on Stackoverflow
Solution 10 - JqueryRemal MahmudView Answer on Stackoverflow
Solution 11 - JqueryAmanverma LuckyView Answer on Stackoverflow
Solution 12 - JquerySean KumarView Answer on Stackoverflow