0

I add a class to div and want to use this added class as condition, but it seems, that it doesn't work:

Here is the code:

<div class="knock">Knock</div>
<div class="msg">Say hello</div>


$( ".knock" ).click(function() {
    $( ".msg" ).addClass( "sayhello" );
});

$( ".msg.sayhello" ).click(function() {
    alert("Hello!");
});

The codepen: https://codepen.io/anon/pen/vwEOoa

Maximilian Neuse
  • 113
  • 3
  • 10
  • the div with class `msg` doesn't have the class `sayhello` when your JS runs, so the listener is not added to it. You can try to set the listener to `.msg` and test with `if($(this).hasClass('sayhello'))` in the handler – Kaddath May 06 '19 at 12:31
  • 1
    Easy answer: use `$(document).on('click','.msg.sayhello', function(){})` – Roy Bogado May 06 '19 at 12:31

2 Answers2

1

Hi because you add this dynamically you must write your code like this:

  $( ".knock" ).click(function() {
    $( ".msg" ).addClass( "sayhello" );
});

$( "body" ).on('click', '.sayhello', function() {
    alert("Hello!");
});
div { cursor: pointer; }
.msg { display: none; }
.msg.sayhello { display: block; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="knock">Knock</div>
<div class="msg">Say hello</div>
Michi
  • 117
  • 5
1

To handle event for dynamically created elements you can use $(document).on() or $(body).on() methods. As shown in below code snippet

$(document).on("click",".sayhello",function(){
  alert("Hello!");
});
Abhishek
  • 866
  • 3
  • 11
  • 19