1

I have a script containing $('a').on('click', function () {alert($(this).attr('class')); }); In my contextmenu function, I create a list with links

$(function () {
$('a').on('contextmenu', function (event) {
        $("<ul id='menu'></ul>")
        .append('<li><a href="#" class="test">Test 1</a></li>')
        .append('<li><a href="">Test 2</a></li>')
        .appendTo("body")
        .css({ top: event.pageY + "px", left: event.pageX + "px" });
        return false;
    });

});

However, the first piece of code (the on click event) does not fire when the link in the list is clicked. However, it fires for every other link on the page. How can I fix this so that my script works on dynamic elements

jpo
  • 3,959
  • 20
  • 59
  • 102
  • Have you tried this? http://stackoverflow.com/a/1207393/742624 – mnoble01 Oct 18 '13 at 19:43
  • Yes, I am using the "on" function and not "live" – jpo Oct 18 '13 at 19:45
  • 1
    right, but notice answer calls `on` on a *containing* element of the dynamic element you want as 'this' in your callback. So something like this should work: `$(document).on('click', 'a', function(){...});`. – mnoble01 Oct 18 '13 at 19:47
  • Tried that too but does not work... – jpo Oct 18 '13 at 19:56
  • 1
    Seems to work: [jsfiddle](http://jsfiddle.net/mnoble01/3ajfc/1/) – mnoble01 Oct 18 '13 at 20:04
  • oh my bad. I change binding on the contextmenu instead on that of the link. THANK you that works. I Will accept any answer you post. – jpo Oct 18 '13 at 20:10

1 Answers1

2

Just a rehash of another SO question.

Calling the jQuery on method on $(document) and providing the 'selector' option will bind the callback to dynamically added elements matching the selector parameter.

That is, this:

$(document).on('click', 'a', function () {
  alert( $(this).attr('class') ); 
});

instead of this:

$('a').on('click', function () {
  alert($(this).attr('class')); 
});
mnoble01
  • 579
  • 5
  • 16