Dale Spiteri Dale Spiteri - 6 months ago 79
jQuery Question

jQuery if/else hasClass (else not working)

I'm trying learn if else statements with jQuery and hasClass. I've done a simple test that won't work and I can't figure out why.

if ($('.one').hasClass('left')) {

$('.button').click(function () {
$('.one').addClass('right');
$('.one').removeClass('left');
})

} else {

$('.button').click(function () {
$('.one').addClass('left');
$('.one').removeClass('right');
})

}


I'm very confused because when I go to the dev tools in Chrome, the first click of the button works fine, and the classes are switched correctly and left is removed. I'm not sure why the else statement won't work though. Everything looks correct to me.

Link to fiddle

Answer Source

You're doing your check before the click, and then the handler always does the same thing.

You want to do your check in the handler:

$('.button').click(function () {
    if ($('.one').hasClass('left')) {
        $('.one').addClass('right');
        $('.one').removeClass('left');
    } else {
        $('.one').addClass('left');
        $('.one').removeClass('right');
    }
});

Or, of course, use toggleClass, but I took it that you're studying if/else...


Side note: I wouldn't re-query like that, I'd remember the set and reuse it (along with chaining):

$('.button').click(function () {
    var one = $('.one');
    if (one.hasClass('left')) {
        one.addClass('right').removeClass('left');
    } else {
        one.addClass('left').removeClass('right');
    }
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download