skip to Main Content

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


  1. Would this work?

    function open() {
      const ev = new Event('beforeopen');
      element.dispatchEvent(ev);
      if (ev.defaultPrevented) return;
      element.setAttribute("data-open", "");
    }
    
    Login or Signup to reply.
  2. 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search