Claire
Claire

Reputation: 3773

Need to add class but only if element is visible

I need to remove all classes of 'no-right-marg' on all #tips li elements. I then need to hide all those elements with a class of the clicked element's ID. Then, I need to check which elements are still being displayed and add a class of 'no-right-marg' to every fourth one. My code below isn't working. Please see my jsfiddle http://jsfiddle.net/VCZc4/2/

jQuery('#selector li').click(function() {

   colour = '.' + jQuery(this).attr('id');
   jQuery('#tips ' + colour).toggle();
   jQuery(this).toggleClass('inactive');
   jQuery('#tips li').removeClass('no-right-marg');

   jQuery('#tips li:visible').each(function(index){

       if(index %4===0 ){// if divisible by 4
           jQuery(this).addClass('.no-right-marg');

       }            
   });

});​

HTML

<ul id="selector">
    <li id="brown">button 1</a>
    <li id="green">button 2</a>
    <li id="blue">button 3</a>
    <li id="orange">button 4</a>

</ul>

<ul id="tips">
    <li class="brown">text</li>
    <li class="orange">text</li>
    <li class="blue">text</li>
    <li class="blue no-right-marg">text</li>
     <li class="blue">text</li>
     <li class="orange">text</li>
     <li class="blue">text</li>
    <li class="blue no-right-marg">text</li>
    <li class="green">text</li>
</ul>
​

Upvotes: 1

Views: 1235

Answers (2)

Jonathan Rowny
Jonathan Rowny

Reputation: 7588

It's zero-indexed, therefore mod 4 == 3 is what you need. if(index % 4 === 0 ) should be if(index % 4 === 3 )

Upvotes: 1

Rey Gonzales
Rey Gonzales

Reputation: 866

There seems to be a "." in your addClass call. Removing the "." fixes your code.

http://jsfiddle.net/reygonzales/VCZc4/5/

I hope that gets what you want.

Upvotes: 6

Related Questions