Search code examples
javascriptjqueryhtmljquery-click-event

jQuery click event works only after second click


I've click event bind to a class called ".reportfile" as follow.

$('body').on('click','.reportfile',function(e){
    e.preventDefault();
    e.stopPropagation();
    var id=$(this).attr('id');
    if(!$(this).hasClass('brc')) {
         // Perform some action here.
    }
});

Now I'm creating LI element dynamically with ".reportfile" class. Like this,

var inLi=$('<li>');
inLi.addClass('reportfile');
$(containerdiv).append(inLi);

Now when I try to click on the dynamic generated LI elements it only works on second click.

https://jsfiddle.net/mt7km8bz/

There is input box on the top of the UL to filter the list. This is where I'm creating new LI dynamically. LI element in filtered list has to be clicked twice to get it working.


Solution

  • The problem was the focus on the input box, on first click input box still have the focus so the click event on list doesn't trigger.

    So on the first click it losses focus on the input box and on second click event get triggered.

    Changes to following worked for me.

    $('body').on('keyup','.searchable',function(){
          // Some code
    });