Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery replace class

Tags:

jquery

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?

like image 720
MiFiHiBye Avatar asked Sep 02 '12 19:09

MiFiHiBye


People also ask

How can I replace one class with another in jQuery?

To replace a class with another class, you can remove the old class using jQuery's . removeClass() method and then add the new class using jQuery's . addClass() method.

Can we replace in jQuery?

We can replace HTML elements using the jQuery . replaceWith() method. With the jQuery replaceWith() method, we can replace each element in the set of matched elements with the provided new content and return the set of elements that were removed.

What is removeClass in jQuery?

The removeClass() method removes one or more class names from the selected elements. Note: If no parameter is specified, this method will remove ALL class names from the selected elements.

How do you change the class of an element?

To change all classes for an element:document. getElementById("MyElement"). className = "MyClass"; (You can use a space-delimited list to apply multiple classes.)


1 Answers

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');
}
like image 134
Austin Greco Avatar answered Oct 27 '22 23:10

Austin Greco