Abhay Nayar
Abhay Nayar

Reputation: 87

Switch animation through 'If Statement' in jQuery

I have some code in jQuery in which I want to make a switch animate on or off by clicking on a div. Here is the code. When I test it, it doesn't work. However if I remove toggle = true on line 7, it just works one way and I can't turn it back off.

$(document).ready(function () {
    $("#switch").click(function () {
        var toggle = false;
        if (toggle == false) {
            $("#circle").css("left", "27px");
            $("#white_rect").attr("src", "green_rect.png");
            toggle = true;
        }
        if (toggle == true) {
            $("#circle").css("left", "1px");
            $("#white_rect").attr("src", "white_rect.png");
            toggle = false;
        }
    });
});

Upvotes: 0

Views: 191

Answers (2)

oxfn
oxfn

Reputation: 6850

It is better to strictly divide appearance and logic. So use .classes and backgounded <div>s instead of <img>. Then you won't need any state variables and code shall be more simple.

HTML:

<div class="container">
    <div class="switch off"></div>
</div>

CSS:

.container {
    width:100%; height:100px; padding:40px; text-align:center;
}
.container .switch {
    width:94px; height: 27px; display:inline-block; background-color:pink; cursor:pointer;
}
.container .switch.on {
    background: url('http://squad.pw/tmp/img/01-on.png') no-repeat 0 0;
}
.container .switch.off {
    background: url('http://squad.pw/tmp/img/01-off.png') no-repeat 0 0;
}

JS:

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

    // Do visual logic
    $(this).toggleClass('on');
    $(this).toggleClass('off');

    // Do business logic
    window.toggle = !window.toggle;
});

Here is FIDDLE

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

You need to declare the toggle variable outside of the click handler... else in every click call the variable will get reinitialized so the value of the variable will always be false.

$(document).ready(function () {
    //declare it here
    var toggle = false;
    $("#switch").click(function () {
        if (toggle == false) {
            $("#circle").css("left", "27px");
            $("#white_rect").attr("src", "green_rect.png");
            toggle = true;
        //also don't use a separate if block here as it will be affected by the execution of the above if block
        } else {
            $("#circle").css("left", "1px");
            $("#white_rect").attr("src", "white_rect.png");
            toggle = false;
        }
    });
});

$(document).ready(function () {
    //declare it here
    var toggle = false;
    $("#switch").click(function () {
        if (toggle) {
            $("#circle").css("left", "1px");
            $("#white_rect").attr("src", "white_rect.png");
        } else {
            $("#circle").css("left", "27px");
            $("#white_rect").attr("src", "green_rect.png");
        }
        toggle = !toggle;
    });
});

Upvotes: 4

Related Questions