This content originally appeared on Go Make Things and was authored by Go Make Things
Yesterday, we looked at how to create custom events for your libraries, components, and scripts. Today, I wanted to explore how to cancel custom events.
Let’s dig in.
What is canceling an event?
If your custom event has the cancelable
option set to true
, you can use the Event.preventDefault()
method to cancel it.
document.addEventListener('my-custom-event', function (event) {
// Cancel the event
event.preventDefault();
});
Inside the bit of code that emitted the event, you can then detect if the event was canceled or not, and change the behavior of your code accordingly.
The Element.dispatchEvent()
method returns false
if the event was canceled, and true if it was not.
let canceled = !document.dispatchEvent(event);
Let’s look at an example.
An example
Let’s imagine you have a function that emits a custom event, then alerts a message. But, if the custom event is canceled
, you don’t want to run the alert()
method.
You would check if the event was canceled
, and if so, end your function.
function sayHi () {
// Create the event
let event = new CustomEvent('my-custom-event', {
bubbles: true,
cancelable: true,
detail: 'This is awesome. I could also be an object or array.'
});
// Emit the event
let canceled = !document.dispatchEvent(event);
// If cancelled, end the function
if (canceled) return;
// Otherwise, alert a message
alert('Hi there!');
}
sayHi();
Inside an event listener, you could cancel the event like this.
document.addEventListener('my-custom-event', function (event) {
console.log('The event was emitted');
event.preventDefault();
});
This is generally reserved for events that are emitted before any actions take place in your library.
This content originally appeared on Go Make Things and was authored by Go Make Things
Go Make Things | Sciencx (2021-04-23T14:30:00+00:00) Canceling custom events with vanilla JS. Retrieved from https://www.scien.cx/2021/04/23/canceling-custom-events-with-vanilla-js/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.