.on()

Objectives:
  • To be aware of event handling issues in dynamic contents
  • To learn a jQuery method that can attach an event handler to both static and dynamic contents

The most effective way to add event handlers to any dynamically, statically rendered HTML content is to use the .on() method. The .on() method works a little differently than the jQuery commands you have practiced up to this point.

Here's a pattern and example:

$(scope).on(event, target element, function(){
  //logic
});
$(document).on('click', 'button', function(){
    alert('you clicked a button!')
});

Notice the above code. It simply means that inside the whole document, if users click to any button, execute the function. Therefore, this click event listener is attached to any button elements of your entire HTML document.

The really neat thing about this .on() function is that every time the event happens in the corresponding target, the relevant parts of the document get scanned in real-time. Thus, any new element added after the page load will be detected and the code will run. Pretty great, huh? Using this method, we can accomplish the same goal for static and dynamic content:

``` $(document).ready(function(){ $('button').click(function(){ $('div...