Alko Alko - 6 months ago 32
jQuery Question

jQuery toggle multiple classes on click

Why I'm not able to toggle multiple classes using onClick event like:

<a data-class="tiny"> Tiny</a>
<a data-class="small"> Small</a>
<a data-class="big"> Big</a>
<a data-class="large"> Large</a>


<i class="icon twitter"></i>


$(document).on('click', 'a[data-class]', function() {
var aclass = $(this).data('class');
$(.box).toggleClass(aclass);
});


On each click I end up with all classes assigned to .icon twitter element, wht I would like to happen is append one of the clicked classes and remove others, but keep the original.

Answer

You may try this adding extra classes and id:

$(document).ready(function(){

  $(".linkClass").click(function(){
  var temp = $(this).id; // contains either tiny, small, big or large

  $(".icon").removeClass("tiny small big large"); // clear any classes added before
  $(".icon").addClass(temp); // adds the required class based on the id of the clicked element.
  });

});
<a class="linkClass" id="tiny"> Tiny</a> 
<a class="linkClass" id="small"> Small</a> 
<a class="linkClass" id="big"> Big</a> 
<a class="linkClass" id="large"> Large</a>


<i class="icon twitter"></i>