jquery - Toggle classes for children of currently active parent element -


right have 3 sections of checkboxes--this example of how section setup:

<div class="color-swatches">       <div class="swatch">         <img src="/img/apothecary_swatch.jpg" class="swatch-icon image">         <p class="color-name">apothecary</p>         <div class="check off"></div>       </div>       <div class="swatch">         <img src="/img/arbor_swatch.jpg" class="swatch-icon image">         <p class="color-name">arbor</p>         <div class="check off"></div>       </div>       <div class="swatch">         <img src="/img/bubble_swatch.jpg" class="swatch-icon image">         <p class="color-name">bubbles</p>         <div class="check off"></div>       </div>       <div class="swatch">         <img src="/img/transparentspacer.gif" class="swatch-icon image">         <p class="color-name">classic</p>         <div class="check off"></div>       </div>       <div class="swatch">         <img src="/img/ladybug_swatch.jpg" class="swatch-icon image">         <p class="color-name">lady bug</p>         <div class="check off"></div>       </div>       <div class="swatch">         <img src="/img/burst_swatch.jpg" class="swatch-icon image">         <p class="color-name">starburst</p>         <div class="check off"></div>       </div> 

.color-swatches contains entire selection of checkboxes section. right now, have things set can click on image (which has class .swatch-icon) , div class .check replace .off class .on 1 (.off has image of inactive checkbox , .on has image of active one).

what need make sure that, each .color-swatches div, 1 swatch-icon "selected" (in other words, on 1 .check div can have .on class @ time). right now, can select or swatches inside .color-swatches div, not want. can alter jquery make functionality happen?

here jquery have @ moment:

(function($) {      $(document).ready(function() {       $('.color-swatches').each(function() {           $('.swatch').each(function(i, n) {              $(n).find('.swatch-icon').bind('click', function(e) {                 e.preventdefault();                  var currentcheck = $(this).find('.check');                  if(currentcheck.hasclass('off')){                   currentcheck.removeclass('off');                   currentcheck.addclass('on');                 }              }.bind($(this)));           });      });    }); }(jquery)); 

you can massively simplify code adding class element clicked , removing other .check elements. try this:

(function($) {     $(document).ready(function() {         $('.swatch-icon').click(function() {             var $container = $(this).closest('.color-swatches');             $container.find('.check').removeclass('on');             $(this).siblings('.check').addclass('on');         });     }); }(jquery)); 

example fiddle


Comments