Custom Event in HTML, Javascript
I am looking to create a custom event in HTML, JS.
<input type="text" oncustombind="foo(event);" /> How can I create one such? "oncustombind" is the custom event that I want to create. I should be able to call the function / code defined in the oncustombind attribute. In addition, I need to pass some data to the event object.
I do not want to use any libraries like jquery, YUI.
Any help would be greatly appreciated.
Do you want customvent
They should be easy to work, but browser support is poor. However, DOM-shim should fix this.
var ev = new CustomEvent("someString"); var el = document.getElementById("someElement"); el.addEventListener("someString", function (ev) { // should work }); el.dispatchEvent(ev); It is bad practice to use new Function and with , but this can be done as follows: http://jsfiddle.net/pimvdb/72GwE/13/ .
function trigger(elem, name, e) { var func = new Function('e', 'with(document) {' + 'with(this) {' + elem.getAttribute('on' + name) + '}' + '}'); func.call(elem, e); } In the following HTML:
<input type="text" oncustombind="console.log(e, type, getElementById);" id="x"> then fire the event as follows:
trigger(document.getElementById('x'), 'custombind', {foo: 123});