Mara Barn Mara Barn - 1 month ago 9
Javascript Question

.click function, remove class after clicked

I have this function so if I click for example "ITEM 1", the "sample1" and "sample3" will become red because have that specific class ("class1").

The problem is that if i click on another item (for example "ITEM2"), the red items of "ITEM1" will remain red and I need them to turn black and highlight in red ONLY the items of current clicked class in the first list.

What to add to below ready(function() in order to do that? Thank you in advance!

<ul>
<li class="leftcol class1">ITEM 1</li>
<li class="leftcol class2">ITEM 2</li>
<li class="leftcol class3">ITEM 3</li>
<li class="leftcol class4">ITEM 4</li>
</ul>

<ul>
<li class="rightcol class1 class4">sample1</li>
<li class="rightcol class2 class3">sample2</li>
<li class="rightcol class3 class1">sample3</li>
<li class="rightcol class4 class2">sample4</li>
</ul>


This is the function:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script>
$(document).ready(function() {
$('.leftcol').click(function() {
$('.rightcol[class*=' + this.className.split(" ").pop() + ']').css('color', 'red');

});
});
</script>

Answer

Use classes to hold the styles, and then just remove the class on all elements, and add it back on the elements matching the class etc

$(document).ready(function() {
  $('.leftcol').click(function() {
    $('.rightcol').removeClass('red')
                  .filter('.'+ this.className.split(" ").pop())
                  .addClass('red');

    });
});
.red {color: red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul>
  <li class="leftcol class1">ITEM 1</li>
  <li class="leftcol class2">ITEM 2</li>
  <li class="leftcol class3">ITEM 3</li>
  <li class="leftcol class4">ITEM 4</li>
</ul>

<ul>
  <li class="rightcol class1 class4">sample1</li>
  <li class="rightcol class2 class3">sample2</li>
  <li class="rightcol class3 class1">sample3</li>
  <li class="rightcol class4 class2">sample4</li>
</ul>