EdwardBlack EdwardBlack - 3 months ago 5
HTML Question

click event handler not working after class changed

If the user clicks on one of the

ul
s then the color and the class should be changing. I solved it with this code, but I noticed that the event handlers are not working anymore after I change the class.

The
ul
s should change their color on each click.



$("ul.AAA").click(function() {
$(this).css("background-color", "yellow");
$(this).removeClass("AAA");
$(this).addClass("BBB");
})

$("ul.BBB").click(function() {
$(this).css("background-color", "blue");
$(this).removeClass("BBB");
$(this).addClass("AAA");
})

div#start {
border: 1px solid black;
cursor: pointer;
}
ul.AAA {
background-color: red;
}
ul.BBB {
background-color: green;
}

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

<ul class="AAA">
<li>
<p>LIST 1</p>
</li>
<li>
<div>
<div>A</div>
<div>B</div>
<div>C</div>
</div>
</li>
</ul>
<ul class="BBB">
<li>
<p>LIST 2</p>
</li>
<li>
<div>
<div>A</div>
<div>B</div>
<div>C</div>
</div>
</li>
</ul>








I also tried it with
on
:



$("ul.AAA").on("click", function() {
$(this).css("background-color", "yellow");
$(this).removeClass("AAA");
$(this).addClass("BBB");
})

$("ul.BBB").on("click", function() {
$(this).css("background-color", "blue");
$(this).removeClass("BBB");
$(this).addClass("AAA");
})

div#start {
border: 1px solid black;
cursor: pointer;
}
ul.AAA {
background-color: red;
}
ul.BBB {
background-color: green;
}

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

<ul class="AAA">
<li>
<p>LIST 1</p>
</li>
<li>
<div>
<div>A</div>
<div>B</div>
<div>C</div>
</div>
</li>
</ul>
<ul class="BBB">
<li>
<p>LIST 2</p>
</li>
<li>
<div>
<div>A</div>
<div>B</div>
<div>C</div>
</div>
</li>
</ul>





How can I solve this problem?

Answer

As you're changing classes dynamically you need to use on(), however you need to use the delegated version of it. Try this:

$(document).on("click", "ul.AAA", function() {
  $(this).css("background-color", "yellow");
  $(this).toggleClass("AAA BBB");
})

$(document).on("click", "ul.BBB", function() {
  $(this).css("background-color", "blue");
  $(this).toggleClass("AAA BBB");
})
div#start {
  border: 1px solid black;
  cursor: pointer;
}
ul.AAA {
  background-color: red;
}
ul.BBB {
  background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul class="AAA">
  <li>
    <p>LIST 1</p>
  </li>
  <li>
    <div>
      <div>A</div>
      <div>B</div>
      <div>C</div>
    </div>
  </li>
</ul>
<ul class="BBB">
  <li>
    <p>LIST 2</p>
  </li>
  <li>
    <div>
      <div>A</div>
      <div>B</div>
      <div>C</div>
    </div>
  </li>
</ul>

Also note the use of toggleClass() over addClass() and then removeClass()