How do I trigger then handle an event in vanilla JavaScript?
What I have tried:
var fireOffAnEvent = function () {
// Dispatch the event.
var custom_event; // The custom event that will be created
if (document.createEvent) {
custom_event = document.createEvent("HTMLEvents");
custom_event.initEvent("custom", true, true);
} else {
custom_event = document.createEventObject();
custom_event.eventType = "custom";
}
custom_event.eventMessage = "Hello events";
document.createEvent ? document.dispatchEvent(custom_event) : document.fireEvent("on" + custom_event.eventType,
custom_event);
}
fireOffAnEvent()
And here is how I have tried to handle the events:
document.addEventListener("custom", function(e) {
console.log(e.eventMessage);
}); // Nothing happened
document.addEventListener("HTMLEvents", function(e) {
console.log(e.eventMessage);
}); // So tried ^, still nothing
Try to fire your events after registering listeners. (put at the end of your code). Then events should be properly handled by them
Try this it works
var fireOffAnEvent = function () {
// Dispatch the event.
var custom_event; // The custom event that will be created
if (document.createEvent) {
custom_event = document.createEvent("HTMLEvents");
custom_event.initEvent("custom", true, true);
} else {
custom_event = document.createEventObject();
custom_event.eventType = "custom";
}
custom_event.eventMessage = "Hello events";
document.createEvent ? document.dispatchEvent(custom_event) : document.fireEvent("on" + custom_event.eventType,
custom_event);
}
// add the listener first
document.addEventListener("custom", function(e) {
console.log(e.eventMessage);
});
// then invoke it
fireOffAnEvent();
Here is the test link http://jsfiddle.net/qikhan/x4r4B/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.