user1355300
user1355300

Reputation: 4987

jQuery Animate through specific div

Is it possible to make an object animate from one position to another using a specific path? For example, while animating from pos1 to pos2, if there is a div with class "no-ok" in the way, it should not go there instead find the nearest div called OK on its left, right, up or down. If there is no div called ok, it should stop. The following image explains:

enter image description here

So far, I can only animate from pos1 to pos2, but I don't know how to check if there's div no-ok in the way, and how to find the nearest div with class ok.

HTML:

  <div class="container">
        <div id="pos1"></div>
        <div class="ok"></div>
        <div class="no-ok"></div>
        <div class="ok"></div>
        <div class="pos2"></div>
    </div>

jQuery:

$('.container').click(function(){
    var pos1 = $('#pos1').position();
    $(this).animate({ 'top': pos1.top + 'px', 'left': pos1.left + 'px'}, 200, function(){
        //end
    });
});

Upvotes: 1

Views: 1262

Answers (1)

Barlas Apaydin
Barlas Apaydin

Reputation: 7315

Animation sturcture needs to be like this:

Here is jsFiddle to play with.

var pTop = parseInt($('.container').css('top'));
var pLeft = parseInt($('.container').css('left'));

$('.container').click(function(){
    var $this = $(this);
    $this.stop().animate({'left': (pLeft * 2) + 'px'},1000,function(){
    //firt step = go 2x right
        $this.stop().animate({'top':  (pTop*3)  + 'px'},2000,function() {
        //second step = go 2x bottom
            $('.container').animate({"left": "-=100px"},1000);
            //third step = go begining left position
        });
    });
});​

Upvotes: 1

Related Questions