The 2 most useful things I learnt at JQuery UK, 2014

It’s been over a month since JQuery UK but I’m using things I learnt there all the time. Here are the two most useful techniques I took away from it.

1. Event delegation. Instead of attaching an event handler to a specific element on the page, letting the event bubble up and handling it on a parent element, usually the document, has several advantages:

  • If attaching a handler to the document you don’t need to wait for document ready.
  • Only one handler needed for multiple elements on the page.
  • No need to attach new handlers when elements are dynamically added to the page.

For example, on a page where new elements with delete buttons are dynamically added, instead of doing this each time a button is added:

$('#new-button').on('click', function() { // delete element });

you can just do this once when the page is first loaded:

$(document).on('click', '.delete-button', function() { // delete element });

2. Initialising components on demand, rather than on page load. This is a good way to increase the speed of the initial page load and not bother initialising features that are never used. For example, initialising a  bootstrap datepicker only when/if a user focuses on the input.

Combining this with event delegation, you can replace this:

$(document).ready( function(){

with this:

$(document).on('focusin', '.datepicker', function (e) {
// check if already initialised
if (typeof ($(this).data('datepicker')) == "undefined") {
// if not, initialise datepicker

Cautionary notes:
The focus and blur events do not bubble up, so for event delegation make sure to use focusin and focusout instead, which do. If you’re listening for user events, make sure these are available with the devices users might be using; it’s no good listening for mouse events if your application is available on touch screen devices!