JQuery – Click() doesn’t work when clicking a
  • in an
    • jquery

      Trying to click an item in a dynamically-generated list, but the $.click() function just won't fire.

      HTML for the list:

      <div>
          <ul id="site_list"> </ul>
      </div>
      

      jQuery to generate the list (which works as intended, generating a long list of data with the desired class attribute):

      var sites =[];
          $.getJSON("php/ABC.php", function(result){
              $.each(result.Sites, function(i,v){
                  sites.push('<li class="site" id="site_'+ ABC + '</li>');
              });
      
              $('#site_list').append(sites.join(''));
          });
      

      jQuery to be triggered when clicking a list (doesn't work…it doesn't throw errors…just fails to respond. I've tried $('#site') as well, to no avail. I suspect it's due to the method I'm using to generate the <ul>…something is preventing the DOM from properly recognizing each element inside the UL.:

      $('li').click(function(){
          $(this).toggleClass("site_selected");
      });
      

      Best Answer

      $('#site_list').on('click', 'li', function(){
          $(this).toggleClass("site_selected");
      });
      

      As you're addling li dynamically so you need delegate event handler to li.


      Note

      Delegate event structure of .on() is like following:

      $(container).on(eventName, target, handlerFunction)
      

      Here container point to a Static-element that contains the target element and belongs to DOM at page load.