0

After the page is loaded, I can add a class with jquery as follows.

$(document).ready(function() {
    $("#parent").click(function(){
        $(".child").addClass("active");
    });
});

but I can't catch the click on the added class, it doesn't work.

$(".child.active").click(function(){
    alert('this is clicked');
});

would you please help me.

1 Answers1

0

Since the child isn't .active when the DOM loads, .child.active does not select any elements, so the event handler to the child isn't added. Add the handler to the .child alone instead, and inside the handler, check if it's active:

$(document).ready(function() {
  $("#parent").click(function() {
    $(".child").addClass("active");
  });
});

$('.child').on('click', function() {
  if ($(this).is('.active')) {
    console.log('this is clicked');
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="parent">
  parent
  <div class="child">
    child
  </div>
</div>

Or add the listener inside the parent click handler instead:

$(document).ready(function() {
  $("#parent").click(function() {
    $(".child")
      .addClass("active")
      .off('click')
      .on('click', function() {
        if ($(this).is('.active')) {
          console.log('this is clicked');
        }
      });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="parent">
  parent
  <div class="child">
    child
  </div>
</div>
CertainPerformance
  • 260,466
  • 31
  • 181
  • 209