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:
JavaScript
x
2
1
<input type="text" onMyFunction="alert('hi');" />
2
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
JavaScript
1
3
1
<input id="foo1" type="text" onMyFunction="alert(this.value);" value="1"/>
2
<input id="foo2" type="text" onMyFunction="alert(this.value);" value="2"/>•
3
JavaScript
JavaScript
1
21
21
1
var winLoad = window.onload;
2
window.onload = function(){
3
var i,
4
elem,
5
fncStr,
6
elems = document.querySelectorAll("[onMyFunction]");
7
8
if (winLoad) {
9
winLoad();
10
}
11
12
for (i=0;i<elems.length;i++) {
13
elem = elems[i];
14
fncStr = elem.getAttribute("onMyFunction");
15
elem.onMyFunction = new Function(fncStr);
16
}
17
18
var tb1 = document.getElementById("foo1");
19
tb1.onMyFunction();•••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••
20
}
21
This code uses querySelectorAll which is not supported in all browsers.