0

So I have the following code:

$("#btn1").click(function(event) {
    event.preventDefault();
    $('html, body').animate({
        scrollTop: $("#div").offset().top
    }, 2000);
    $("#div").addClass("flash");
    setTimeout( function(){
        $("#div").removeClass("flash"), 1000;
    }, 1000);
});

When I click on the button it will scroll down to the div and flash its color (flash class). But what if the div is at the bottom of the page? I need the ode above to be changed so that the scrollTop is executed first AND is finished and then execute the next piece of code (the addClass and the setTimeout function). I assume I need to add a delay? Or something that checks whether the function is complete and if so, start the next one?

PowerUser
  • 812
  • 1
  • 11
  • 32
  • Here's a couple questions that might help: http://stackoverflow.com/questions/22547888/jquery-animate-and-done http://stackoverflow.com/questions/19359763/done-after-animate-callback-function – phenomnomnominal Jun 21 '15 at 12:05

2 Answers2

0

I think what you're looking for is animation callback. It's the forth parameter to the .animate() method: http://api.jquery.com/animate/

So in your case it would look like this:

$("#btn1").click(function(event) {
    event.preventDefault();

    $('html, body').animate({
        scrollTop: $("#div").offset().top
    }, 
    2000, 
    'swing', 
    function () {
        $("#div").addClass("flash");
        setTimeout( function(){
            $("#div").removeClass("flash"), 1000;
        }, 1000);
    });

});

Btw. it's a good practice to cache a jQuery selectors for optimisation (jQuery won't be searching the DOM for the queried nodes, and running the its constructor function each time).

I also refactored this code a bit for readability and to separate the flashing functionality, so you can either use it conveniently in such callbacks (in which case the function will get the animated element as this object, or just run it directly, passing it any jQuery element (e.g. flash($('.anything')))

$("#btn1").click(function(event) {
    event.preventDefault();

    $div = $('#div');
    $('html, body').animate({
        scrollTop: $div.offset().top
    }, 2000, 'swing', flashElement});
});

function flashElement(element) {
    element = element || this;
    element.addClass("flash");
    setTimeout( function(){
        element.removeClass("flash"), 1000;
    }, 1000);
}
Tomek Sułkowski
  • 7,081
  • 2
  • 17
  • 15
0

You just need a callback...

$("#btn1").click(function(event) {
    event.preventDefault();

    $('html, body').animate({
        scrollTop: $("#div").offset().top
    }, 2000, function(){
     $("#div").addClass("flash");
        setTimeout( function(){
            $("#div").removeClass("flash"), 1000;
        }, 1000);  
    });
});
Nahum
  • 101
  • 6