Mohammad Riyad
Mohammad Riyad

Reputation: 29

Jquery changing class and trigger

<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.

Upvotes: 0

Views: 102

Answers (2)

4b0
4b0

Reputation: 22323

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>

Upvotes: 3

Pushprajsinh Chudasama
Pushprajsinh Chudasama

Reputation: 7949

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'); 
    });
});

Upvotes: 3

Related Questions