Skip to content
Advertisement

How to add listener for a custom event in the DOM?

What I want is to create my own function that will be bound as an event listener similar to how other event listeners (e.g., onclick) are set:

<input type="text" onMyFunction="alert('hi');" />

Is it possible and if so how?

Advertisement

Answer

The problem you have is the browser does not realize it is a function in there. It is a string, the only way you can make it a function is to assign it as a function.

One way is either on document ready or onload, you query the document for elements with the attribute and reassign it.

HTML

<input id="foo1" type="text" onMyFunction="alert(this.value);" value="1"/>
<input id="foo2" type="text" onMyFunction="alert(this.value);" value="2"/>​

JavaScript

var winLoad = window.onload;
window.onload = function(){
    var i, 
        elem,
        fncStr,    
        elems = document.querySelectorAll("[onMyFunction]");

    if (winLoad) {
        winLoad();
    }

    for (i=0;i<elems.length;i++) {
        elem = elems[i];
        fncStr = elem.getAttribute("onMyFunction");
        elem.onMyFunction = new Function(fncStr);        
    }

    var tb1 = document.getElementById("foo1");
    tb1.onMyFunction();​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
}

Example running here

This code uses querySelectorAll which is not supported in all browsers.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement