I am trying to create a custom Javascript event. The event works and fires correctly, but the 'detail' object that I'm passing it is not available.
Here's the code I'm using to create and dispatch the event:
var double_tap = new CustomEvent("doubleTap", {
detail: {
hello: 'world'
},
bubbles: true,
cancelable: true
});
this.dispatchEvent(double_tap);
Then I'm using jQuery to add an event listener to the body:
$('body').on('doubleTap', function( e ) {
console.log(e);
});
It does fire, and the console log happens, but unfortunately the log only outputs the event details including bubbles and cancelable properties, but never the 'detail' object, so that information is not accessible.
Here's a jsbin as example, I'm creating the event on the click event of the body so you can see the console; http://jsbin.com/looseroots/6
I would like to be able to get the data from the 'detail' object when the event is fired. What am I doing wrong? I have tested this in Chrome, and Safari on iOS.
To create a custom event, you use the CustomEvent () constructor: let event = new CustomEvent (eventType, options); Code language: JavaScript (javascript) The CustomEvent () has two parameters:
You can dispatch custom events like so: To listen for the custom event, add an event listener to the element you want to listen on, just as you would with native DOM events. How do JavaScript custom events work?
The CustomEvent () has two parameters: The eventType is a string that represents the name of the event. The options is an object has the detail property that contains any custom information about the event. The following example shows how to create a new custom event called highlight:
We can not only assign handlers, but also generate events from JavaScript. Custom events can be used to create “graphical components”. For instance, a root element of our own JS-based menu may trigger events telling what happens with the menu: open (menu open), select (an item is selected) and so on.
obj.addEventListener("eventName", function(e) {
console.log(e.your_property)
})
var event = new CustomEvent("eventName");
event.your_property = { key: "value" };
obj.dispatchEvent(event);
You can create properties in your CustomEvent, when you dispatch you are sending it.
You need to access the originalEvent property for the details
console.log(e.originalEvent.detail);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With