0

After dynamically adding elements using .append in a .ajax() call, not all of the elements that should be registered are being recognized by my .on('click, '.order_notes', ... ) call.

When I run the code .on('click', '.order_notes', ...) only it registers with the 3/4 of my elements with the class 'order_notes', all of them at the bottom of the generated page. The first 1/4 of the elements that I should be able to click on, all of them at the top of my generated page, don't register. I think I'm running into a race condition. Can anyone offer some insight into what is happening or how I might work around this problem?

The function being called on document load:

function getOrders(){

$.ajax({                                      
  url: path+'/ajax/orders.php',          
  data: "",                        
  dataType: 'json',                   
  success: function(data){  

    $('#content').empty();

    var output = "";
    var currentDate = "";
    var keeper = 0;

    for (var i in data){

        var id = data[i]['id'];
        var tId = data[i]['transaction_id'];
        var shop = data[i]['store'];
        var type = data[i]['type'];
        var msg = data[i]['msg'];
        var timestamp = data[i]['timestamp'];

        var datetime = timestamp.split(" ");
        var date = datetime[0];
        var time = datetime[1];

       if(keeper == 0){
            output+="<div class=daily_order_record><b>" + date +"</b></br>";
            currentDate = date;
            keeper++;
        }

       if(currentDate != date && keeper != 0){
            output+="</div><div class=daily_order_record><b>" + date +"</b></br>";
            currentDate = date;
            keeper++;
        }

      output +="<p class=\"order_notes\" id=t_"+ tId +">" + time + "  " + shop + "  " + msg + "</p>"; 

  }

  $('#content').hide().append(output).fadeIn(500); 

  }

 });    
}

The code registering .on click handlers:

$(document).ready( function() {

  $(document).ajaxComplete(function() {
      $('html').on('click', '.order_notes', function(){

          alert("hi");
      });
  });

});

Additional Code that I have tried to register .on click handlers with the same result:

$(document).ready( function() {

  $('html').on('click', '.order_notes', function(){
      alert("hi");
  });

});
RoJG
  • 49
  • 3
  • Hi there. It looks like the answer below was useful to solving this problem. Would you consider accepting it? If you wish to do so, click the tick mark to the left of the question, so that it turns green. It's how we mark questions as solved here (and it rewards the answerer a little too). Thanks! – halfer Feb 25 '15 at 09:13

1 Answers1

2

Put your on event handler outside the ajaxComplete callback, but still inside the document.ready. The idea of on is that it will listen past the original DOM creation/ready point, including all elements loaded by AJAX after this point:

$(document).ready(function() {
    $('html').on('click', '.order_notes', function() {
        alert('hi');
    });
    $(document).ajaxComplete(function() {
        // whatever else you do in your callback
    });
});

Another thing to note is that you are currently assigning that click handler to .order_notes elements within the html element - this is a very large scope and bubbling will occur across many levels. You could do better to narrow down your target by using the #content div instead of html as a base so your event handler:

$('#content').on('click', '.order_notes', function() {});
Community
  • 1
  • 1
scrowler
  • 24,273
  • 9
  • 60
  • 92
  • Instead of saying "past" and "after" you should be referring to "children" or "descendants." – pmandell May 21 '14 at 20:27
  • Thanks for the response! Though, I should have clarified that I had tried that only to run into the same issue. – RoJG May 21 '14 at 20:45
  • Try going against my second note there and capture from the entire document down - `$(document).on('click', '.order_notes', function() {});` - if that doesn't work, there is likely to be an outlying problem. – scrowler May 21 '14 at 20:53
  • Thanks, your clarification regarding proper implementation was very helpful. You were correct about it being an outlying problem. The culprit was a negative z-index setting my stylesheet for #content. – RoJG May 21 '14 at 22:03
  • Glad you nailed it down! – scrowler May 21 '14 at 23:08