4

I have a situation where an element loads on the page(dynamically added by some third party) and have defined certain event for that element.

Below is the code which mimics the same situation where the .on() is not working on an element which I am adding dynamically.

What can be the issue here?

// 1
$('#bhansa').click(function(){
  console.log('first');
})

// 2
$('.dom').on('click', '#bhansa', function(){
  console.log('second');
})

setTimeout(function(){
  $(".dom").html("<a href='#' id='bhansa'>Click me</a>");
}, 4000);

// 3
$('#bhansa').on('click', function(){
  console.log('last');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="dom"></div>
bhansa
  • 6,166
  • 2
  • 23
  • 42
  • 2
    Possible duplicate of [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – peeebeee Aug 17 '18 at 14:46

3 Answers3

4

Use event delegation on the body tag to make sure the event will not be detached when you remove/add parts to you DOM structure :

$('body').on('click', '#bhansa', function(){
     console.log('second');
})

As @Taplar comment says if the element that you are delegating binding on is being created dynamically, you are binding too low and should bind on a higher parent that is not dynamic body.

Zakaria Acharki
  • 63,488
  • 15
  • 64
  • 88
2

the problem is that if you remove dom component, all listeners are removed also.
Try to add listener this way:

$("body").on("click", "#bhansa", () => {console.log(123)})
dorintufar
  • 538
  • 6
  • 20
0

You can write like this also:-

$(document).find().on('click', '#bhansa', function(){
    //code
});

Here document is Dom object.