How to stop jquery animation based on CSS values?

So, I have two divs: # div1 and # div2. I want "# div2" to disappear when "# div1" has a CSS value: top = 0px.

Here is the CSS:

#div1 {
    top: 0px;
}
#div2 {
    display: block;
} 
if ( $('#div1').css('top') == '0px' ) {
    $("#div2").hide();
} else {
    $("div2").fadeIn();
}
$("div2").click(function(){
        $("#div1").animate({top:"+=315px"}, "slow");
});

The problem I am facing is that I am changing the CSS value (for # div1) using Javascript, and for this reason my js don't confirm the changes and don't make the div disappear (I think) Is there a way to make # div2 disappear when # div1 CSS property top = 0 and reappear whenever it changes? Or is there a better way to implement this?

+5
source share
3 answers

instead of using this use method .position()

<script>
var p = $("#div1");
var position = p.position();
alert( "left: " + position.left + ", top: " + position.top );
</script>

: http://api.jquery.com/position/

+3

:

$("div2").click(function(){

        $("#div1").parent().css({postion,"relative"});

        $("#div1").css({postion,"absolute"});

        $("#div1").animate({top:"+=315px"}, "slow");
});

# div1 , # div1 .

+1

Just use callbacks

#div1 {
    top: 0px;
}
#div2 {
    display: block;
}

$("div2").click(function(){
        $("#div1").animate({top:"+=315px"}, "slow", function(){
             if($('#div1').position().top < 1){
                  $('#div1').hide();
             }else{
                  $('#div1').fadeIn('slow');
             }
        });
});
+1
source

All Articles