Create and use jquery custom events
Creating custom events in jQuery is quite easy, all you have to do is figure out how to name your custom event and when to trigger it. In 2 steps you can create your custom event.
Here is code example of how to create it.
You need to select one or more DOM elements and attach the event listener to it:
$('#myElement').bind('myEventName', function() { // what to do when event occurs // });
and you need to trigger your event:
$('#myElement').trigger('myEventName');
Simple, isn't it?
But how will i use it, and more important, why should i use it?
Ok, let's create some practical example. Lets say that in my code i have some functionality that changes classes of some elements often, now i want that evey time i change the class of some element to highlight that same element.
There are many ways to do this, but here is one example of not using custom events and one where you use them.
NOT USING CUSTOM EVENT
function hightlightElement(el) { $(el).effect( 'highlight', {color: '#6699FF'}, 500 ); } if($('#myElement').removeClass().addClass('newClass')) { hightlightElement($('#myElement')); }
USING CUSTOM EVENT
$('*').bind('classChanged', function() { $(this).effect( 'highlight', {color: '#6699FF'}, 500 ); }); $('#myElement') .removeClass() .addClass('newClass') .trigger('classChanged');
Now, this way your code looks more professional, more readable, and most important it will not brake the jQuery chain if you decide that you need to perform more operation on your selected element.
$('#myElement') .removeClass() .addClass('newClass') .trigger('classChanged') .find('p:first') .empty();
There are many usages for custom events, this one is trivial but if you decide that you want to create your own jQuery plugins for general usage, you may find custom events very usefull in interaction with your plugin potencial users. For example, if you are creating some dialog plugin, you can create events for dialog open, dialog close etc. that your users can use on their own without modifing your plugin.