Custom event in HTML, Javascript

9.4k views Asked by At

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.

2

There are 2 answers

0
Raynos On BEST ANSWER

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);
7
pimvdb On

It's bad practice to use new Function and with, but this can be accomplished 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);
}

With the following HTML:

<input type="text" oncustombind="console.log(e, type, getElementById);" id="x">

then trigger the event like:

trigger(document.getElementById('x'), 'custombind', {foo: 123});