Search code examples
jqueryjquery-on

jQuery on() method with click and element class name triggerred anywhere on the page


Recently I've upgraded jQuery to 1.9 and my main problem now is to convert all live() methods to on().

I've succeeded in a few situation, but I have some other methods that just behave very strange.

Take the following as an example:

$(document).on('click', '.clickReplace', function(e) {
     e.preventDefault();
     ...
});

The class 'clickReplace' can be assigned to either 'a', 'span' or 'div' tag and it might be added to the DOM after ajax call (dynamically).

When I use the above, every click on any of the links on the page that doesn't have this class assigned triggers the e.preventDefault() - I cannot navigate between the pages - as if it was binded to the 'document' rather than the element within the document tree with the specified class.

Any idea what might be causing it and what should I do to make it work?


Solution

  • My sincere apologies to everyone - you're absolutely right - there was something different that was causing this behaviour and it was the fact that I was passing the object with the class rather then the class name as the second argument (as it's a method inside of the object literal, which was called externally with the parameter indicating which element should be triggered).

    I had it this way, which is obviously not going to work:

    $(document).on('click', $('.clickReplace'), function(e) {
    

    Thanks everyone for participating.