Domanda

I have a column of boxes. When individual boxes are clicked, toggling of animation and background color occur. How could I get other elements (such as a close button) to animate all boxes back to their default positions? The JS I'm using is below.

JSFIDDLE: http://jsfiddle.net/SgDwn/59/

var $boxes = $(".box").click(function () {
    var $this = $(this),
        left = parseFloat($this.css('left')) || 0;
    if (left == 0) {
        $this.stop(true).animate({left: "100px"}).css('background','blue');

        $boxes.not(this).stop(true).animate({left: 0}).css('background','red');

    } else {
        $this.stop(true).animate({left: 0});
È stato utile?

Soluzione

Alex beat me, but I would say make a function and use "each" to call the function on each fo the boxes:

var $boxes = $(".box").click(function () {
    var $this = $(this),
        left = parseFloat($this.css('left')) || 0;
    if (left == 0) {
        $this.stop(true).animate({left: "100px"}).css('background','blue');

        $boxes.not(this).stop(true).animate({left: 0}).css('background','red');

    } else {
        MoveLeft();
    }
});

function MoveLeft() {
        $(this).stop(true).animate({left: 0});
        $(this).css('background','green');
}

$(".close").click(function () {
    $boxes.each(MoveLeft);
});

UPDATE:

corrected the link, fiddle: http://jsfiddle.net/SgDwn/62/

Altri suggerimenti

You kinda had the code already:

$(".close").click(function() {
    $boxes.stop(true).animate({left: 0}).css('background','red');
});

Cleaned up a bit:

var $boxes = $(".box");

$boxes.click(function () {
    var $this = $(this),
        left = parseFloat($this.css('left')) || 0;
    if (left == 0) {
        $this.stop(true).animate({left: "100px"}).css('background','blue');

        $boxes.not(this).stop(true).animate({left: 0}).css('background','red');

    } else {
        $this.stop(true).animate({left: 0});
        $this.css('background','green');
    }
});

$(".close").click(function() {
    $boxes.stop(true).animate({left: 0}).css('background','red');
});

Fiddle

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top