1

I have this bit of code that monitors clicks on <div class="selectable_item">

$(function(){
  $("#matchres .selectable_item").on("click", function(){
    console.log('Sending request')
    $.post("/request", $.param({'crit_id': this.id}), function(){}).fail(function(){console.log("matchres error...");});
    return true;});
});

What I'm noticing is when I use the chrome console, for example, to see if there are any $("#matchres .selectable_item"); it finds them, and if I define in the console $("#matchres .selectable_item").on("click", function(){console.log('hi')}); the action is as expected and the console logs correctly. But what I showed you above does not work. Any ideas why that is? Any help would be very much appreciated. As added information, I'm using jquery v1.10.2.

Cenoc
  • 11,172
  • 21
  • 58
  • 92

2 Answers2

3

@Hanlet's idea is correct, at the time of document load those items don't exist because you're dynamically creating them, and they do exist by the time you interact with them in the developer console. What you want to do is bind the event handler to a delegate, or an object that will listen for events on child elements.

What you do not want to do is add delegate callbacks to the document when avoidable. Any click on the document will have to check against its event target to see if it should trigger this document delegate callback. You do this enough times and it becomes a performance concern. Instead, pick the closest ancestor element that isn't dynamically created.

For instance, if you're creating .selectable_item dynamically but not #matchres, then add this:

$('#matchres').on('click', '.selectable_item', function () { ... });
Joseph Spens
  • 668
  • 7
  • 12
1

Because you add these dynamically, this could be an event delegation issue, very common. Try this instead:

$(document).on("click", "#matchres .selectable_item", function(){ ... }

The problem consists mainly in the fact that you bind these when the DOM is first built, and then you add more elements dynamically, but the event is not bound to these new elements.

Look at these two examples:

http://jsfiddle.net/hescano/aKfWf/

and

http://jsfiddle.net/hescano/aKfWf/1/

Hanlet Escaño
  • 17,114
  • 8
  • 52
  • 75