Search code examples
jqueryjquery-on

jQuery .on() sometimes works, sometimes not


I have weird problem. At first I didn't want to use .on() method because I couldn't get it to work at all, so I used .live().

Now, I'm writing a new jQuery script and I used .on() heavily and it works. Until now.

jQuery code:

   $('#artistList a').on('click',function(e){
    console.log($(this).parent().text());
    e.preventDefault();
   });

HTML Code:

<div id="artistList">
 <div class="artist"><a class="delete" href="#"></a>Psy</div>
 <div class="artist"><a class="delete" href="#"></a>Fernanda Martins</div>
 <div class="artist"><a class="delete" href="#"></a>DJ Nreal</div>
</div>

Also tried this methods:

   $('#artistList>a').on('click',function(e){
   $('.delete').on('click',function(e){

No luck. What am I missing?

This is the only part that doesn't work

I have read the documentation about .on() and based on that, this should work. Also, I'm using the latest jQuery, (jquery-1.8.3.min.js).

EDIT

<a> elements have a width: 15px and height: 15px in CSS, so they are visible.


Solution

  • In order to work like live you need to delegate the handler to a higher level element.

     $('body').on('click','#artistlist a', function(e) {
         // note the change to the selector to reflect your actual mark up
         // handler body
     });
    

    Using this form of on is required if the elements to which the handler should apply are added dynamically after the page is initially loaded. Note also that the handlers should be applied after the DOM is loaded either by placing scripts just before the end of the body element or using the ready event handler, $(function() { ... });

    If a handler sometimes works and sometimes doesn't it's likely a race condition on page load between the elements being loaded into the DOM and the script being invoked. This is usually a sign that you've omitted adding the handlers inside the ready event handler.