/* Add an event handler of some sort to an object so that we have a means of triggering the event. */ document.querySelector('button').onclick = function(e) { // Create an event of the type CustomEvent var evt = document.createEvent('CustomEvent'); /* Parameters for initCustomEvent: initCustomEvent( eventType, canItBubble, isItCancelable, detailAboutEvent); Internet Explorer 9+ requires the fourth parameter, but can be null (as shown below). Without it, IE will throw an error. Versions of Internet Explorer < 9 do not support DOM Level 3 */ evt.initCustomEvent('bounce', false, false, null); // Dispatch the event on an object, in this case the document document.dispatchEvent(evt); }; /* Add an event listener to the object on which you've dispatched an event. */ document.addEventListener('bounce', function(e) { // Do something when the event is fired. document.querySelector('#result').innerHTML += 'A bounce event was fired!<br>'; }, false);
<!DOCTYPE html> <html lang="en-us"> <head> <meta charset="UTF-8"> <title>Custom DOM Events Example</title> </head> <body> <h1>Custom DOM Events Example</h1> <button>Click me :-)</button> <div id="result"></div> </body> </html>
body{ font: 90% / 1.5 sans-serif; } h1{font-size:2em; font-weight:bold;} button{ background:#606; color:#fff; border:2px outset #606; font: inherit; } button:hover{ background:#909; color:#fff; border:2px outset #909; font: inherit; } #result{ background:#eee; margin:1em auto; padding: .5em; }