jqueryjquery-delegate

jQuery event delegation for when a selector comes into existence?


Let's say I want to change the text of any new particular DOM elements that are created. E.g.:

(not real API, I realize)

$('body').on('creation', '.change-this', function() {
  $(this).text('Boom!');
});

So if I programmatically create <p class="change-this"> and add it to the DOM (via jQuery or otherwise), the above fires off. Is this something jQuery can do? All I can think of, is when I add whatever HTML programmatically, to do a $.trigger('creation') and have a handler ready to take care of those events.


Solution

  • You want to track your brand new items? You can do this using custom events. Since you are using jQuery, you may use the method .trigger() to create your event.

    For instance, you will need to trigger your event every time you create your element. So, in your code you will add something like this:

    ... // Your code goes here
    new_item = '<p class="change-this">'; // The DOM that you will inject
    container.append(new_item); // Injecting item into DOM
    container.trigger('creation', []); // Firing a event signaling that a new item was created
    ...
    

    Then, you will create a listener for this custom event:

    container.on('creation', function() {
        console.log("Yay! New item added to container!");
    });
    

    Check this snippet:

    $('#add').on('click', function() {
    
      var item = '<p>New item</p>',
          container = $('#container');
      
      container.append(item);
      container.trigger('creation');
    });
    
    
    $('#container').on('creation', function () {
      var new_message = 'New Item added!<br>';
      
      $('#message').append(new_message);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button id="add">add</button>
    <b id="message"></b>
    <div id="container"></div>

    Bear in mind that if you want to track elements with custom tracks, you just need to create different custom events and handle its triggers.

    So, that's it. jQuery provide us a simple and beautiful way to work with custom events. Awesome!

    For further information, you may check these links: jQuery.trigger() - http://api.jquery.com/trigger/

    Introducing Custom Events - http://learn.jquery.com/events/introduction-to-custom-events/

    CustomEvent - https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent

    Good Luck!