Custom event in HTML, Javascript

varunvs picture varunvs · Oct 28, 2011 · Viewed 7.8k times · Source

I'm 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 I want to create. I should be able to call the function/code defined in the oncustombind attribute. Also, I need to pass some data to the event object.

I don't want to use any libraries such as jquery, YUI.

Any help would be deeply appreciated.

Answer

Raynos picture Raynos · Oct 28, 2011

You want a CustomEvent

They should be easy to work with but browser support is poor. However the DOM-shim should fix that.

var ev = new CustomEvent("someString");
var el = document.getElementById("someElement");
el.addEventListener("someString", function (ev) {
    // should work
});
el.dispatchEvent(ev);