Skip to content

Instantly share code, notes, and snippets.

@nobitagit
Created November 19, 2014 08:36
Show Gist options
  • Save nobitagit/195920184f17ad990525 to your computer and use it in GitHub Desktop.
Save nobitagit/195920184f17ad990525 to your computer and use it in GitHub Desktop.
Creating an event in javascript and firing it programmatically
// creating an event and firing it programmatically
document.addEventListener('change', function(e) {
console.log(e.someProp);
});
var event1 = document.createEvent('HTMLEvents');
event1.initEvent('change',true,false);
event1.someProp = 'yourPropHere';
inputEl.dispatchEvent(event1);
// Polyfill from MDN, see: https://developer.mozilla.org/en/docs/Web/API/CustomEvent
(function () {
function CustomEvent ( event, params ) {
params = params || { bubbles: false, cancelable: false, detail: undefined };
var evt = document.createEvent( 'CustomEvent' );
evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
return evt;
};
CustomEvent.prototype = window.Event.prototype;
window.CustomEvent = CustomEvent;
})();
document.addEventListener('name-of-event', function(e) {
console.log(e.detail); // Prints "Example of an event"
});
// Create the event
var event = new CustomEvent('name-of-event', { 'detail': 'Example of an event' });
// Dispatch/Trigger/Fire the event
document.dispatchEvent(event);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment