Wednesday, June 1, 2011

How to create your Custom Event in jQuery

If you have used jquery before, I believe you should be very familiar with using events like the following:-

$('.myClass').click(function(e){
    e.preventDefault();
    // doing something here
});

or

$('.myOtherClass').bind('mouseenter', function(e) {
    e.preventDefault();
    // doing something here
});

But do you know that you can create your own Custom Event and call it just like a standard events.

$('.myAnotherClass').bind('SuperClick', function(e) {
    e.preventDefault();
    // doing something here
});

and somewhere in your code, you can call your custom event 'SuperClick' like this

$('.myAnotherClass').trigger('SuperClick');

That's it, you can bind your custom event to your element (object), and next time when you trigger that custom event, your stuff will run. However, don't think too complicated if you are still not sure what's going on... Think of it as if you are just creating a javascript function and you can reuse that function whenever you call it.

But there is a catch when you use this type of custom event, make sure you trigger the custom event using the same element.  The reason is you bound the custom event to an object (element), and only that element can listen to that custom event.  Make sense?

No comments:

Post a Comment