Skip to content

Instantly share code, notes, and snippets.

@pec1985
Created May 29, 2011 04:25
Show Gist options
  • Save pec1985/997465 to your computer and use it in GitHub Desktop.
Save pec1985/997465 to your computer and use it in GitHub Desktop.
Custom Event in browser JavaScript
// tested only in safari. Use at your own risk.
Element.prototype.fireEvent = function(a,b) {
b = b || {};
b.type = a;
b.source = this;
var evt = document.createEvent("Events");
evt.initEvent(a, true, true);
for(var i in b){
if(b){ evt[i] = b[i]; }
}
evt.value = b;
this.dispatchEvent(evt);
};
//======== Example =========
var btn = document.createElement('button');
btn.addEventListener('pedro', function(e){
alert(e.hello); // alerts "world"
});
btn.addEventListener('click', function(){
btn.fireEvent('pedro', { hello: 'world' });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment