LadyCoder
LadyCoder

Reputation: 336

Listening to a custom event in javascript

i was reading an article on the MDN website talking about how to customise an events in javascript https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events and i was able to create this

const evt = new CustomEvent("swipe", {
    detail: {
       color: "red"
     }
});

documet.addEventListener("swipe", e => {
        console.log(e.detail);
    });

document.dispatchEvent(evt);

But the problem is, the event got triggered immediately, how can i stop this by defining what a swipe really is? for example, i want the event to be triggered when someone click on the screen but i still want to use the swipe word as it's listener.

Upvotes: 0

Views: 964

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074345

...i want the event to be triggered when someone click on the screen...

You'd use a click (or mousedown) handler to trigger your swipe event:

document.addEventListener("click", e => {
    document.dispatchEvent(new CustomEvent("swipe", {
        detail: {
           color: "red"
         }
    }));
});

Live Example:

document.addEventListener("click", e => {
    document.dispatchEvent(new CustomEvent("swipe", {
        detail: {
           color: "red"
         }
    }));
});

document.addEventListener("swipe", e => {
    console.log(e.detail);
});
Click anywhere on the document.

Upvotes: 5

Related Questions