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

2 Answers 2

3

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

$(document).on('click', ops.editbuttonselector, function(e) {
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Thanks for the more complete answer. Your solution also worked and with other benefits.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.