1

I have this HTML:

<div class="bold knowmore login" id="j-6">
<span>...</span>
</div>

and this jQuery:

$(function(){
  $(".login").on("click", function(){ 
     console.log('login clicked!');
     $(".bold.knowmore").removeClass("login").addClass("displayAdvert");
  });

  $(".displayAdvert").on("click",function(){
    console.log("display was clicked!");
  }); 
});

But the output is always:

login clicked!

But, for some reason, the HTML is updated but the event always calls the click login. Someone has an idea how I can resolve it?

Garrett Kadillak
  • 1,026
  • 9
  • 18
Benjamin RD
  • 11,516
  • 14
  • 87
  • 157
  • Hi, where do you have the `displayAdvert` at first? – naota Jun 16 '14 at 14:55
  • Just type your question title plus 'jquery' into google and you'll find pages of solutions, one of which being this: http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements – Joe Jun 16 '14 at 14:56
  • @naota, the displayAdvert is attached dynamically when you click the first time the login div and the login is removed – Benjamin RD Jun 16 '14 at 14:56

3 Answers3

4

You need to use a A delegated-events approach

You're assigning the .displayAdvert class dynamically so you need to use .on method with dynamic element delegation:

I suppose you have a static parent in your story, so use it's ID:

$(function(){
  $(".login").on("click", function(){ 
     console.log('login clicked!');
     $(".bold.knowmore").removeClass("login").addClass("displayAdvert");
  });

  $("#parent").on("click", ".displayAdvert", function(){
    console.log("display was clicked!");
  }); 
});

http://api.jquery.com/on/#direct-and-delegated-events

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
  • You can also just use body instead of a parent's ID – Shmoopy Jun 16 '14 at 14:56
  • 2
    @Shmoopy you can use also `$(document)` but it's too expensive to listen for a bubbling click all the way up the DOM tree also probably triggering unecessary listeners binded to other elements (like in the case of a `body` click listened by a popup... just for example...). – Roko C. Buljan Jun 16 '14 at 14:56
  • @Shmoopy, the wider you make the parent element, the less control you have and the worse the performance. – DevlshOne Jun 16 '14 at 14:57
2

Uses Event Delegation becouse you are adding a class Dynamicly:

$(function(){
  $(document).on("click",".login", function(e){ 
      e.preventDefault();
     console.log('login clicked!');       $(".bold.knowmore").removeClass("login").addClass("displayAdvert");
  });

  $(document).on("click", '.displayAdvert',function(e){
      e.preventDefault();
    console.log("display was clicked!");
  }); 
});

DEMO

Wilfredo P
  • 4,070
  • 28
  • 46
1

For dynamically created elements you can use something like the following:

$(document).on("click", ".displayAdvert", function() {
    console.log("display was clicked");
});
lucasjackson
  • 1,515
  • 1
  • 11
  • 21