12/15/2014 - 10:30 AM

Event Binding with jQuery

Event Binding with jQuery

//nav menu toggle
//list of space-separated hook names on an element
<button data-hook="nav-menu-toggle video-pause click-track">Toggle Nav Menu</button>
<nav data-hook="nav-menu">
        <li><a href="/">West Philadelphia</a></li>
        <li><a href="/cab">Cab Whistling</a></li>
        <li><a href="/throne">Throne Sitting</a></li>
$('[data-hook="nav-menu-toggle"]').on('click', function() {

  • or
    hook: function(hookName) {
        var selector;
        if(!hookName || hookName === '*') {
            // select all data-hooks
            selector = '[data-hook]';
        } else {
            // select specific data-hook
            selector = '[data-hook~="' + hookName + '"]';
        return $(selector);

function toggleNavMenu() {
$.hook('nav-menu-toggle').on('click', toggleNavMenu);

//finding any hook name
$.hook('click-track'); // returns the button as expected

//selecting all hook elemenents on page
// both are equivalent

Working with Multiple Events

list of events to be handled by a single event handler:

$.hook('nav-menu-toggle').on('click keydown mouseenter', trackAction);

handling multiple events with different event handlers, using object notation:

    'click': trackClick,
    'keydown': trackKeyDown,
    'mouseenter': trackMouseEnter

unbinding multiple events at same time:

// unbinds keydown and mouseenter
$.hook('nav-menu-toggle').off('keydown mouseenter');
$.hook('click-track').off('click', trackClick);
// nuclear option: unbinds everything

using namespaces:

// binds a click event in the "analytics" namespace
$.hook('click-track').on('', trackClick);
// unbinds only click events in the "analytics" namespace

multiple namespaces:

// binds a click event in both the "analytics" and "usability" namespaces
$.hook('click-track').on('', trackClick);
// unbinds any events in either the "analytics" OR "usability" namespaces
$.hook('click-track').off('.usability .analytics');
// unbinds any events in both the "analytics" AND "usability" namespaces

// free all elements on the page of any "analytics" event handling