Read, With the Name of Your Lord Who Created

Archive for February 14th, 2008

Javascript Events: Programmatically vs. Declaratively

Posted by triaslama on February 14, 2008

In the past few days I was enjoyed learning Javascript and I quite interested when I read about Javascript event! The Javascript event is a bit different from the events I knew before, and I guest it quite powerful too.
Look at the simple example:
when we declares an event programmatically we can do this (it works for IE and non IE browsers):

<html>
<head>
<title>Hello Javascript</title>
<script lang=”javascript” type=”text/javascript”>
document.onclick = function(e)
{
e = e||window.event;
window.alert(e.type);
};
</script>
</head>
<body>
</body>
</html>

We need do a reguler check with this line of code:

e = e||window.event;

because Internet Explorer (IE) recognize an event object throught the property of object window named ‘event’ so when we want to get the event object in IE programmatically it can be accomplished using ‘window.event’.

We can change the name of ‘e’ parameter above with the name we like (such ‘event’, ‘evt’, ‘myParameter’, etc.), and the code will still work fine.

but when I do this :
<html>
<head>
<title>Hello Javascript</title>
<script lang=”javascript” type=”text/javascript”>
function test(e)
{
window.alert(e.type);
}
</script>
</head>
<body>
<input type=”button” id=”btn” value=”Test” onclick=”test(e)” />

</body>
</html>

I type the path in browser’s address bar and click the button but the ‘e’ parameter is undefined! Then I wonder why, because in my opinion the event handler always receive one parameter (that is the event object itself).
As an experiment I change the code above so it looks like the following
<input type=”button” id=”btn” value=”Test” onclick=”test(event)” />
And now the code just work fine! What happen? is that Javascript event so strange like this?

So I do a litle experiment on how to declare event programmatically (through javascript code) and declaratively (through html tag), and then I found the answer.
When we declare events programmatically the event handler function can accept zero parameter (no parameter required), or the event handler function can accept one parameter (the event object itself).
When we declare events declaratively (specify the event handler inside a html tag, such as <input type=”button” onclick=”clickHandler()” />) we can pass any number of parameters, but when we want to pass the event object as parameter we must pass it as ‘event’ nothing else!

I think this is quite interesting story from Javascript event, and I hope I can find more interesting things. See you…

(Tri Sugiyantowo / triaslama).

Posted in Javascript | Tagged: , , , , | 2 Comments »