Event Listeners and Binding

jQuery On Delegated

/**
 * jQuery 'On' Delegated
 *
 * An event-delegation approach to 'on' attaches an event handler
 * to only one outer element (#my-nav), and the inner element's
 * event ('click' on 'a.item') only bubbles up one level.
 * This also allows you to dynamically add new "a.item" elements
 * to '#my-nav' which will immediately bind.
 */
$( "#my-nav" ).on( "click", "a.item",
    function( e )
    {
        e.preventDefault( e ); // Stops the normal element action.
        console.log( $( this ).text() );
    }
);

jQuery On

/**
 * jQuery 'On'
 *
 * 'on' can attach to almost any element and listen for almost any event.
 */
$( "a.button" ).on( "click",
    function( e )
    {
        e.preventDefault( e ); // Stops the normal element action.
        console.log( $( this ).text() );
    }
);

Native JS Event Listener

/**
 * Native Javascript Event Listener.
 *
 * elem: The object you want to listen to.
 * type: The event you want to listen to.
 * functionName: The name of the function to call when the event is fired.
 */
var addEvent = function(elem, type, functionName)
{
    if (elem == null || typeof(elem) == 'undefined') return;
    if ( elem.addEventListener ) {
        elem.addEventListener( type, functionName, false );
    } else if ( elem.attachEvent ) {
        elem.attachEvent( "on" + type, functionName );
    } else {
        elem["on"+type] = functionName;
    }
};

// Use examples:

// Bind a function to the 'window' 'load' event.
addEvent( window, "load", someFunctionName );
 
// Bind a function to the 'window' 'resize' event.
addEvent( window, "resize", someFunctionName );

Inline Binding


/**
 * Attach a function directly to an inline element's event.
 */
<a href="javascript:void(0)" onclick="myJsFunction();">Run JavaScript Code</a>