jQuery - Custom Event


  • How can we define custom events on custom objects?

What is custom event?

No. Event handling is not only applicable to DOM elements (or UI elements). It is for back-end programming too. It is known as "event driven", observer / dispatcher pattern. jQuery allows event driven architecture to be applied to javascript object, as well as native object. See Custom Event

jQuery allows us to bind and trigger events on any object (including Javascript objects).

The window.location is a Javascript object that contains information about the URL including hash and search strings. Let's use jQuery to bind a "change" event directly to the window.location object.

In the code, the author use a timer to detect if window.location.hash had changed:

setInterval( fnCheckLocation, intIntervalTime );

In the fnCheckLocation() function, he perform some logic (compare current value with previous value), then he trigger the "change" event on window.location:

$( window.location ).trigger(

To use jQuery to bind "change" event listeners directly to the window.location Javascript object:

$( window.location ).bind(
    function( objEvent, objData ){
        var jLog = $( "#log" );


Key take away points:

Event isn't necessarily associated with DOM element. It is applicable to normal javascript objects, native objects, and other programming languages as well. This is called event-driven architecture / pattern. Also known as observer / dispatcher pattern.

For browser that does not support the hash changed event, we can simulate it.

If we don't like to use setInterval, we can use event delegation on all <a> element with the click event. We then check to see if this would result in a hash change, and trigger the change event. For dealing with the back button, we might be able to use the onload event. But then how would we differentiate the onload that is caused by the back button, and the onload that is caused by the normal page load? If you click on a named anchor link, the browser update its history, and the back button takes you back to where you were. In this situation, does the onload event get fired when you click on the back button?

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License