Saturday, August 28, 2010

Javascript Events

Events and event handlers are very important for JavaScript programming. Events are mostly caused by user actions. If the user clicks on a button a click-events occurs. If the mousepointer moves across a link a Mouseover-event occurs. There are several different events. we want our JavaScript program to react to certain events. This can be done with the help of event-handlers. A button might create a popup window when clicked. This means the window should pop up as a reaction to a Click-event. The event-handler we need to use is called onClick. This tells the computer what to do if this event occurs. The following code shows an easy example of the event-handler onClick:

<form>
<input type="button" value="click me" onClick="alert('Yo')">
</form>

There are a few new things in this code - so let’s take it step by step. You can see that we create a form with a button (this is basically a HTML-problem so I won’t cover it here). The new part is onClick="alert(’Yo’)" inside the <input> tag. As we already said this defines what happens when the button is pushed. So if a Click-event occurs the computer shall execute alert(’Yo’).
This is JavaScript-code (Please note that we do not use the <script> tag in this case). alert() lets you create popup windows. Inside the brackets you have to specify a string. In our case this is ’Yo’. This is the text which shall be shown in the popup window. So our script creates a window with the contents ’Yo’ when the user clicks on the button.
One thing might be a little bit confusing: In the document.write() command we used double quotes" and in combination with alert() we use only single quotes ’ -why? Basically you can use both. But in the last example we wrote onClick="alert(’Yo’)" - you can see that we used both double and single quotes. If we wrote onClick="alert("Yo")" the computer would get confused as it isn’t clear which part belongs to the onClick event-handler and which not. So you have to alternate with the quotes in this case. It doesn’t matter in which order you use the quotes - first double quotes and then single quotes or vice versa. This means you can also write onClick=’alert("Yo")’.

There are many different event-handlers you can use. We will get to know some during this tutorial- but not all. So please refer to a reference if you want to know what kind of other event-handlers do exist.

If you are using the Netscape Navigator the popup window will contain the text JavaScript alert. This is a security restriction. You can create a similar popup window with the prompt() method. This window accepts an input. A malicious script could imitate a system message and ask for a certain password. The text in the popup window shows that the window comes from your web browser and not from your operating system. As this is a security restriction you cannot remove this message.

No comments:

Post a Comment