JQuery trigger() Method : How to Create Custom Events in jQuery

Share this article

In my previous article, How to Create Custom Events in JavaScript, we discussed the benefits of custom events and the native CustomEvent object. To recap, we can fire our own named events. The demonstation page provided a form which fired a “newMessage” event whenever a valid message was submitted. Any number of handlers can subscribe to this event to perform their own actions. Our only problem: CustomEvent is not currently supported in Safari or Internet Explorer. There are ways around the browser compatibility issue. One solution is to write your own event encapsulation functions which implement custom event functionality. Fortunately, there’s no need: custom events are supported in several JavaScript libraries including jQuery. jQuery’s .trigger method is the key. You can trigger an event with a new type name and arbitrary data at any point, e.g.


$.event.trigger({
	type: "newMessage",
	message: "Hello World!",
	time: new Date()
});
Handlers can now subscribe to “newMessage” events, e.g.

$(document).on("newMessage", newMessageHandler);

Demonstration Page

This example demonstrates the jQuery code: View the jQuery Custom Events demonstration page A standard event handler looks for submissions on an HTML form. The function gets the current message and, assuming it’s valid, dispatches a new “newMessage” event.

$("#msgbox").on("submit", SendMessage);

// new message: raise newMessage event
function SendMessage(e) {

	e.preventDefault();
	var msg = $("#msg").val().trim();
	if (msg) {
		$.event.trigger({
			type: "newMessage",
			message: msg,
			time: new Date()
		});
	}

}
Handlers can now subscribe to “newMessage” events. The events are only raised if there’s a valid message:

// newMessage event subscribers
$(document).on("newMessage", newMessageHandler);

// newMessage event handler
function newMessageHandler(e) {
	LogEvent(
		"Event subscriber on "+e.currentTarget.nodeName+", "
		+e.time.toLocaleString()+": "+e.message
	);
}
The message itself can be extracted from the message property of the event object.

Browser Compatibility

jQuery 1.x methods run in any browser including Internet Explorer 6.0 and above. Obviously that’s a huge bonus even if the code runs (un-noticeably) slower than native CustomEvents. However, be aware that jQuery 2.0, planned for release in 2013, will not support IE6, 7 and 8. jQuery is popular, but custom events are supported in most JavaScript libraries including Prototype, Mootools and YUI. And if you enjoyed reading this post, you’ll love Learnable; the place to learn fresh skills and techniques from the masters. Members get instant access to all of SitePoint’s ebooks and interactive online courses, like jQuery: Novice to Ninja: New Kicks And Tricks.
Comments on this article are closed. Have a question about jQuery? Why not ask it on our forums?

Frequently Asked Questions (FAQs) about jQuery Custom Events

What are jQuery Custom Events and why are they important?

jQuery Custom Events are user-defined events that allow developers to create and manage their own events in addition to the standard events provided by jQuery. They are important because they provide a way to encapsulate behavior that can be reused across different parts of an application. This can lead to cleaner, more maintainable code by reducing duplication and promoting separation of concerns.

How do I create a custom event in jQuery?

Creating a custom event in jQuery is straightforward. You can use the .trigger() method to trigger a custom event. Here’s a simple example:

$(document).trigger('myCustomEvent');

In this example, ‘myCustomEvent’ is the name of the custom event.

How can I pass data to a custom event handler in jQuery?

You can pass data to a custom event handler in jQuery by providing an additional argument to the .trigger() method. This argument can be any JavaScript object. Here’s an example:

$(document).trigger('myCustomEvent', { key: 'value' });

In this example, the object { key: 'value' } is passed to the event handler.

How do I handle a custom event in jQuery?

You can handle a custom event in jQuery by using the .on() method. Here’s an example:

$(document).on('myCustomEvent', function(event, data) {
console.log(data.key); // 'value'
});

In this example, the function provided to the .on() method is the event handler.

Can I stop a custom event from propagating in jQuery?

Yes, you can stop a custom event from propagating in jQuery by calling the .stopPropagation() method on the event object. Here’s an example:

$(document).on('myCustomEvent', function(event) {
event.stopPropagation();
});

In this example, the stopPropagation() method prevents the event from bubbling up the DOM tree.

Can I prevent the default action of a custom event in jQuery?

Yes, you can prevent the default action of a custom event in jQuery by calling the .preventDefault() method on the event object. Here’s an example:

$(document).on('myCustomEvent', function(event) {
event.preventDefault();
});

In this example, the preventDefault() method prevents the default action associated with the event.

Can I trigger a custom event only once in jQuery?

Yes, you can trigger a custom event only once in jQuery by using the .one() method instead of the .on() method. Here’s an example:

$(document).one('myCustomEvent', function() {
console.log('This will only be logged once.');
});

In this example, the event handler will only be called once, even if ‘myCustomEvent’ is triggered multiple times.

Can I remove a custom event handler in jQuery?

Yes, you can remove a custom event handler in jQuery by using the .off() method. Here’s an example:

$(document).off('myCustomEvent');

In this example, all handlers for ‘myCustomEvent’ on the document are removed.

Can I trigger a custom event manually in jQuery?

Yes, you can trigger a custom event manually in jQuery by using the .trigger() method. Here’s an example:

$(document).trigger('myCustomEvent');

In this example, ‘myCustomEvent’ is triggered manually.

Can I bind multiple handlers to a custom event in jQuery?

Yes, you can bind multiple handlers to a custom event in jQuery by calling the .on() method multiple times with the same event name. Here’s an example:

$(document).on('myCustomEvent', function() {
console.log('Handler 1');
});

$(document).on('myCustomEvent', function() {
console.log('Handler 2');
});

In this example, both handlers will be called when ‘myCustomEvent’ is triggered.

Craig BucklerCraig Buckler
View Author

Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler.

CustomEventeventsHTML5 Dev CenterJavaScriptjQuery
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week