0

I'm trying to move a div by clicking a button and have an alert pop up when the top margin is a certain value. However, the alert only pops up after I am moving it away from the margin I want.

Here is the code that I am using:

$("input.down").click(function()
    $(".block").animate({"margin-top": "+=50px"});
    check();
});

$("input.up").click(function(){
    $(".block").animate({"margin-top": "-=50px"});
    check();
});

function check(){
    var top = $(".block").css("margin-top");

    if (top == "100px") {
        alert('top: ' + top + '\nyou have the right height');
    }
}

When I initially move the margin-top to 100px there is no alert, but once I move it away from there, there is an alert. Its like the check function if run first and then the div is animated. Is there a way to make it so it is animated first?

0

3 Answers 3

1
$("input.down").click(function() {
   $(".block").animate({"margin-top": "+=50px"}, function() { check(); });
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot, this worked. I'm curious to know why putting check() inside of a function would allow the animation to happen first
in my code, check() is performed when the animation completes; but in your code, check() is performed just after the animation starts. in that case, as the animation is not completed, check() will find that the <div> is not at 100px, so it won't alert message. but when you click it again, animation starts, check() runs, this time, message is alerted because the <div> is at 100px in the last animation.
0

Try this:

$("input.down").click(function(){
       $(".block").animate({"margin-top": "+=50px"}, {"complete": check});
    });

This should run the check function once the animation is complete.

Comments

0

IMHO, I'll do:

    $("input.down").click(function()
       var marginTop = $(".block").css("margin-top");
       $(".block").animate({"margin-top": marginTop + 50}, function() {
            check();
       });           
    });

   $("input.up").click(function(){
       var marginTop = $(".block").css("margin-top");
    $(".block").animate({"margin-top": marginTop - 50 }, function() {
            check();
       });          
    });

  function check(){
   var top = $(".block").css("margin-top");

   if (top == "100px") {
   alert('top: ' + top + '\nyou have the right height');
  };}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.