Forum Moderators: open
If I want to trap events, but not inline like:
<p onclick="dosomething();">Click Me to Do Something</p>
How would I go about doing it?
In VBScript, this would be the answer:
<script language="vbscript">
function Test_onClick
alert("Hi")
end function
</script><p id="Test">Hi</p>
A very simple function whose name matches the object you want to trap, followed by _eventName. How can I duplicate this in javascript?
Thanks.
[pre]
window.onload = function()
{
document.getElementById('test').onclick = testOnClick;
// document.getElementById('test').onclick = function(eMoz){ alert('I am '+this.id) };
}function testOnClick(eMoz) // Mozilla sends the event as arg
{
alert('I am '+this.id)
}
[/pre]
The alternative assigns an anonymous function to it. This is OK sometimes, but the first doesn't have context problems.
There are newer methods that can assign methods that don't override each over:
[element].attachEvent // IE
[element].addEventListener // standards
The IE one has a drawback in that the call context reverts to global, so there's no useful 'this' keyword.