Javascript events

Now that you understand functions, variables and objects you are ready to learn a bit more about handling events in JavaScript.

Multiple events

Add this to the existing page (variables.html) leaving the paragraph which is already there:

<div  onmouseup="fred()" style="height:300px; width:400px; background-color:red;">
    <p>Click anywhere in this DIV</p>        
</div>        
        

Now place a new function in the HEAD section. The function click() needs to be set up inside the SCRIPT tags in the HEAD above or below the existing function (larger). You can have lots of functions in the HEAD:

            
function fred(){                
    alert('Mouse clicked');
}        
        

Save the page and click on the DIV. The ONMOUSEUP or ONMOUSEOVER attributes you have used so far are known as event triggers. They "call" some code. For most of the examples on these pages you have "called" functions. You can attach any number of event triggers which call any number of functions (which are the event handlers). The thing to watch out for is not to have a trigger (e.g. ONMOUSEUP) triggered from an element inside another element which also has the same trigger. The method of event handling taught here does not know how to handle that conflict.

There is another way to handle events but that is not yet fully supported by all common browsers. You will learn it later.

Other events

These event triggers are fairly commonly used:

Replace the current events in your page (variables.html) with each of these in turn and experiment with them. Don't panic if the two keyboard ones do not work as that is explained next.

Keyboard events

The keyboard ones may not work as key presses are "sent" to the active program. If the browser is not the current application in use on your system the key press will never reach the event trigger. Even if the browser is the active application the page needs to be selected and if the event trigger is attached to one element in the page that element needs to have the focus. You can give it the focus by clicking on it with the mouse.

For keyboard events to be useful you probably need to know which key was pressed but that gets complicated as different browsers do it differently. It will be covered very soon.

Mouse over events

These are very popular for some reason. They can be used to create buttons or links which react to the presence of the mouse cursor. They can also cause other images to change or for larger images to show when thumbnails are hovered over. However, CSS can be used for these as well and without the added burden of JavaScript to slow the browser down.

submit to reddit Delicious Tweet