MiFiHiBye
MiFiHiBye

Reputation: 190

jQuery replace class

I have a large list of <li>'s that are given a width from a 'span3' class.

<ul class="thumbnails">
    <li class="span3">
        <div class="thumbnail"><img src="/images/logos-s/s-001.png" alt="" data-creator="swc"> <span>01</span></div>
    </li>
    repeat...40x
</ul>

I have buttons (button#grid-bigger && button#grid-smaller) that allow the users to increase and decrease the size of the grid on click. Ideally, the user would be able to click three times, and each time it would change the <li> class from span3 to span4 then to span12.

Here's the JavaScript:

$('#grid-bigger').live('click', function (e) {
    $('#blob .thumbnails').find('li').each(function(i, ojb) {
        if ( $(this).hasClass('span2') ) {
            $(this).removeClass('span2').addClass('span3');
        }

        if ( $(this).hasClass('span3') ) {
            $(this).removeClass('span3').addClass('span4');
        }

        if ( $(this).hasClass('span4') ) {
            $(this).removeClass('span4').addClass('span12');
        }
    });
});

What happens is that instead of allowing separate clicks to the "make bigger" button, it'll only click once and execute two of the statements at the same time.

Any suggestions?

Upvotes: 18

Views: 60578

Answers (1)

Austin Greco
Austin Greco

Reputation: 33544

you just need to use else if, otherwise they will all execute in order:

if ( $(this).hasClass('span2') ) {
    $(this).removeClass('span2').addClass('span3');
} else if ( $(this).hasClass('span3') ) {
    $(this).removeClass('span3').addClass('span4');
} else if ( $(this).hasClass('span4') ) {
    $(this).removeClass('span4').addClass('span12');
}

Upvotes: 40

Related Questions