Skip to main content Accessibility Feedback

emit.js

Emit a custom event.

Source Code

Example

window.addEventListener('my-library:custom-event', function (event) {
	console.log(event.detail);
}, false);

emit('my-library:custom-event', {
	greeting: 'Hello, world!'
});

The helper function

/**
 * Emit a custom event
 * (c) Chris Ferdinandi, MIT License, https://gomakethings.com
 * @param  {String} type   The event type
 * @param  {Object} detail Any details to pass along with the event
 * @param  {Node}   elem   The element to attach the event to
 */
function emit (type, detail = {}, elem = document) {

	// Make sure there's an event type
	if (!type) return;

	// Create a new event
	let event = new CustomEvent(type, {
		bubbles: true,
		cancelable: true,
		detail: detail
	});

	// Dispatch the event
	return elem.dispatchEvent(event);

}

How it works

Learn more about custom events.


Find this useful? You can support my work by purchasing an annual membership.