Forum Moderators: open

Message Too Old, No Replies

Event Trapping Question

but not inline

         

Lance

3:00 pm on Oct 8, 2004 (gmt 0)

10+ Year Member



I've been writing VBScript for a very long time, but now having seen the error of my ways I'm trying to switch entirely to javascript for client-side scripting.

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.

Bernard Marx

6:26 pm on Oct 8, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You can't quite do it like that, but almost.
You need to make sure that the element has been parsed before assigning a method to it.
(There are one or two purely IE approaches that avoid this, but let's ignore them)

[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]


Make sure you use all lower case for event names.

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.

Lance

10:01 pm on Oct 8, 2004 (gmt 0)

10+ Year Member



Okay, I get it...

Thanks BernardMarx!