0

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
  <span class="fake_h">Too</span>
</body>

<script>
  $('.fake_h').click(function() {
    $(this).addClass('active_h').removeClass('fake_h');
  })
  $('.active_h').click(function() {
    alert()
  })
</script>

When I click on span it removes the class fake_h and add active_h. But after that when I click span(class='active_h') It doesn't work. Don't trigger alert or anything. Can anyone explain why it doesn't work.

4b0
  • 21,981
  • 30
  • 95
  • 142
  • `$(body).on("click", '.active_h', function(){ alert(123) })` – dandavis Sep 18 '19 at 05:27
  • 2
    Possible duplicate of [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Carl Binalla Sep 18 '19 at 05:28

2 Answers2

3

You can do it like this.

$(document).ready(function(){
    $('.fake_h').click(function(){
       $(this).addClass('active_h');
       $(this).removeClass('fake_h');
    });

    $('body').on("click", '.active_h', function(){ 
       alert('active_h'); 
    });
});
Pushprajsinh Chudasama
  • 7,772
  • 4
  • 20
  • 43
3

Wrap your span with some div and use that div class to trigger your dynamic added class. Changing the identifiers dynamically need to use delegated event handlers.

$('.yourClass').on("click", '.fake_h', function() {
  $(this).addClass('active_h').removeClass('fake_h');
})
$('.yourClass').on("click", '.active_h', function() {
  alert()
})
.active_h {
  text-decoration: underline
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class='yourClass'>
  <span class="fake_h">Too</span>
</div>
4b0
  • 21,981
  • 30
  • 95
  • 142