1

I need to add a click handler to a dynamic added link. I have read that the click method from JQuery does not work for dynamically created elements (and actually I could not get it to work).

I have the following code:

$(this).find(ops.editbuttonselector).click(function(e) {

As the .live method is now deprecated, I would need to use .on for this. According to this thread and my undersntanding of jquery (which is limited), I should do:

selector = $(this).find(ops.editbuttonselector) 
$(document).on('click', selector, function(e) {

But this also did not work and actually what was working before (existing elements) stopped working as well.

Can someone please point me to the right syntax.

thanks in advance

Community
  • 1
  • 1
duduklein
  • 10,014
  • 11
  • 44
  • 55

2 Answers2

3

The second parameter to .on() is a selector string, not a jQuery object:

$(document).on('click', ops.editbuttonselector, function(e) {
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
1

Since you bind it using $(this), I assume that you are trying to add the handler after the element had been added to DOM.. if that is the case then you can simply do like below,

//below is direct binding which is better than delegated event
$(this).find(ops.editbuttonselector).on('click', function(e) {

Else if this is the parent element which exist in DOM when below line is executed,

//this is delegated event binding method
$(this).on('click', ops.editbuttonselector, function(e) {

else you can .on to the closest parent which might exist in DOM or document object.

You can read more about when and why you should bind to document object https://stackoverflow.com/a/12824698/297641

Community
  • 1
  • 1
Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134