Evan Levesque
Evan Levesque

Reputation: 3213

How to interrupt jQuery animate?

I am trying to animate a div when clicking on the document using jQuery by increasing the x-position of that div.

I don't want the div to go out of my sight while it is animating; if the div went out of my screen I want to bring it back.

This is my code:

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
body{
    overflow: hidden;
}
div {
    position: absolute;
    left:10px;
    top:10px;
    width:20px;
    height:20px;
    background-color:green;
}
</style>
<script type="text/javascript">
$(function(){
    $(document).click(function(){
        if($("div").offset().left > (parseInt($(window).width()))){
            $("div").animate({"top":'+=20'},1000);
            $("div").animate({"left": '8' },1000);
        }else{
            $("div").animate({"left":'+=400'},1000);
        }
    });
});
</script>
</head>
<body>
<div></div>
</body>
</html>

Upvotes: 1

Views: 387

Answers (1)

Imdad
Imdad

Reputation: 6042

Refer http://jsfiddle.net/YV747/3/

$(function(){
    $(document).click(function(){
        $("#pointer").stop(0,0);

        if(($("#pointer").offset().left+100) > $(window).width()){
            $("#pointer").animate({"top":'+=20',"left":8},1000);
            //$("#pointer").animate({"left": '8' },1000);
        }else{
            $("#pointer").animate({"left":'+=400'},1000);
        }
    });
});

see the line if(($("#pointer").offset().left+100) > $(window).width()){

I have given 100 there you can give 400 or any value that suits you.

Note: Do not use code on simply div always use id otherwise it will act on all the divs in the document.

Upvotes: 4

Related Questions