Marcolac
Marcolac

Reputation: 931

Slide div. Jquery

I'm using this code to slide divs off the screen:

       $('.box').click(function() {

            $(this).animate({
                 left: '-50%'
             }, 500, function() {
            $(this).css('left', '150%');
            $(this).appendTo('#container');
            });

            $(this).next().animate({
                 left: '50%'
            }, 500);
       });

html:

     <div id="container">

     <div id="box1" class="box">Div #1</div>
     <div id="box2" class="box">Div #2</div>
     <div id="box3" class="box">Div #3</div>


      </div>

css: .box { position: absolute; left: 150%; margin-left: -25%; }

       #box1 {

         left: 50%;
       }

It works great. But when I click on the last div, the first one comes back and I can go over all the div again.

I would like it to stop when the last div appears. Could you give me hints on how I can accomplish that?

Thank you for your help.

Upvotes: 0

Views: 556

Answers (1)

Sushanth --
Sushanth --

Reputation: 55750

I think you are looking for .one()

$('.box').one('click' , function() {

Also it's a better practice to cache the reoccurring selectors to reduce the number of times you query the DOM

$('.box').one('click', function() {
    var $this = $(this);
    if (this.id !== 'box3') {
        $this.animate({
            left: '-50%'
        }, 500, function() {
            $this.css('left', '150%');
            $this.appendTo('#container');
        });

        $this.next().animate({
            left: '50%'
        }, 500);
    }
});​

Check Fiddle

Upvotes: 1

Related Questions