The following code is a simplified version of a module I am making where I want to implement custom "beforeopen" and "beforeclose" events. I want to be able to listen to these events, and cancel the open or close methods from continuing from inside the eventlistener function. For standard events, you can just do e.preventDefault() to cancel the default behavior assosiated with the event. This of course does not work for my custom event, but I want to know how I can make it work. Can I tell my event what the default action assosiated with the event is anyhow? Or are there other workarounds to make this work.
const element = document.querySelector(".element");
const openButton = document.querySelector(".openButton");
function open() {
element.dispatchEvent(new Event("beforeopen"));
// if default is prevented, I want to stop the function from continuing!
element.setAttribute("data-open", "");
}
element.addEventListener("beforeopen", (e) => {
e.preventDefault();
});
openButton.addEventListener("click", () => {
open();
});
.element {
display: none;
}
.element[data-open] {
display: block;
}
<div class="element">Element opened - Failed to prevent default</div>
<button class="openButton">Open</button>
2
Answers
Would this work?
You need to set the
cancelable
flag of your newEvent
object, afterward, you can callpreventDefault()
on it and check itsdefaultPrevented
attribute.