On this MDN page Creating and Triggering Events it shows an example of creating event with Event
or CustomEvent
. It explains that CustomEvent
allows for custom details, but other than that, it doesn't say much.
So, what is the difference? If I'm creating a generic scroll event, should I use CustomEvent
? Or is it only for events not exist in javascript?
Also, I noticed that MouseEvent
is also a child of Event
, so if I'm creating a click event, I can just use new MouseEvent('click')
?
Thanks
On this MDN page Creating and Triggering Events it shows an example of creating event with Event
or CustomEvent
. It explains that CustomEvent
allows for custom details, but other than that, it doesn't say much.
So, what is the difference? If I'm creating a generic scroll event, should I use CustomEvent
? Or is it only for events not exist in javascript?
Also, I noticed that MouseEvent
is also a child of Event
, so if I'm creating a click event, I can just use new MouseEvent('click')
?
Thanks
Share Improve this question edited Apr 24, 2015 at 20:21 Evan Davis 36.7k7 gold badges52 silver badges58 bronze badges asked Apr 24, 2015 at 20:18 BigNameBigName 1,1072 gold badges17 silver badges29 bronze badges2 Answers
Reset to default 5From that guide:
To add more data to the event object, the
CustomEvent
interface exists and thedetail
property can be used to pass custom data.
You can use Event()
for anything. If you want to attach custom data, you use CustomEvent('eventName', {data})
.
And yes, for mouse-events, you should use MouseEvent
.
In all modern browsers:
const ev = new Event('foo')
ev.whatever = 123
console.log('event:', ev.whatever)
We can simply use Event
directly like that, or even extend from Event
to make a custom event:
class MyEvent extends Event {
whatever = 123
constructor() {
super('my-event', {bubbles: true, posed: true, cancelable: false})
}
}
someElement.dispatchEvent(new MyEvent()) // simple and done.
Nowadays there is absolutely no need for CustomEvent
to even exist, and we can just use Event
.
In the past, it may not have been possible to extend from Event
using pre-ES6 function
classes, but this limitation has long since been overe in all browsers, and class
es can extend from native classes.