How can i define my own event in jQuery?
Refer to this link.
Here are some code snippet from the article above.
You can trigger custom events on any DOM object of your choosing using jQuery. Just trigger it using the following code:
$("#myelement").trigger('fuelified');
You can subscribe to that event using either bind or live functions in jQuery:
$("#myelement").bind('fuelified',function(e){ ... });
$(".cool_elements").live('fuelified',function(e){ ... });
You can even pass additional data about the event when triggering it and reference it on the listeners end:
$("#myelement").trigger('fuelified',{ custom: false });
$("#myelement").bind('fuelified',function(e,data){ if(data.custom) ... });
The element the trigger has been called on, is available to listener’s callback function as the variable this.
Define and attach your own custom events with .bind():
// make myObject listen for myFancyEvent
$('#myobject').bind('myFancyEvent', function(){
alert('Yow!');
});
...then .trigger() them directly:
$('#myobject').trigger('myFancyEvent');
...or mixed in with other event handlers:
$('#myobject').click( function(){
doSomething();
$(this).trigger('myFancyEvent');
});
You shouldn't have trouble finding a lot of information on the subject. This article is a couple of years old, but still a good overview.
You can throw events like this:
$("#element").trigger("your.event", [ 'Pamela', 'Anderson' ] );
Note that extra parameters should be passed as an array.
How to listen for events:
$("#element").bind("your.event", function(event, firstName, lastName) {
// Callback
});
The "#element" selector can be substituted with document if the event isn't specific for a particular dom node.