Skip to content

Instantly share code, notes, and snippets.

@jongrover
Created July 23, 2014 21:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jongrover/2279676f978c5bbaf21c to your computer and use it in GitHub Desktop.
Save jongrover/2279676f978c5bbaf21c to your computer and use it in GitHub Desktop.
live_event_listener.js
// Regular event listener applys a listener once at the moment the DOM loads and the document is ready.
$('button').click(function(){});
// Under the hood jQuery really calls the on() method.
$('button').on('click', function(){});
// The Problem
// Both of these methods as-is are not live event listeners as they are called once when the DOM loads.
// The problem is that when using AJAX if we insert new elements into the DOM after the page has already loaded,
// These new <button> elements did not previously exist when we first set event listeners on them.
// For this reason they will have no effect when we click on them. Onl buttons that existed when the document first loaded will have the listeners.
// The solution
// jQuery provides us with a way to add live event listeners to elements that are asychronously added to the DOM at any point in time.
// Live Event Listener using additonal argument to the on() method.
$('body').on('click', 'button', function() {});
// This first selects the <body> element which is a parent we have intentionally selected as it will not chnage after the DOM has loaded. For the live event selector to work we need to select any parent element that will not change after the DOM loads and where we expect children to dynamically and asynchronously be inserted at a later point in time.
// Then we use the on() method. For its first argument we specifiy the event type in this case 'click', the second argument sets the child that will asychronously appear later and which we want to add the click event listener too.
// So to be clear: we are adding the click lsitener to <button> not to <body>.
// Basically we are asking jQuery to watch the <body>, and when any new <button> children appear in the DOM we will apply a click listener to them. Problem solved. We can now append new buttons into the DOM as we please at any moment and they will all have proper event listeners applied to them.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment