Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I "preventDefault" for custom events

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>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You need to set the cancelable flag of your new Event object, afterward, you can call preventDefault() on it and check its defaultPrevented attribute.

const element = document.querySelector(".element");
const openButton = document.querySelector(".openButton");

function open() {
  const evt = new Event("beforeopen", { cancelable: true });
  element.dispatchEvent(evt);
  if (evt.defaultPrevented) {
    console.log("prevented");
    return;
  }
  // 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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading