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?
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.
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.
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.
To change all classes for an element:document. getElementById("MyElement"). className = "MyClass"; (You can use a space-delimited list to apply multiple classes.)
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');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With