Javascript events
In Javascript, an event is an action performed on a webpage by the user such as clicking a button or entering text into a textbox. Event handlers are used to detect these events and act upon them accordingly.
This lesson focuses on:
- Event handlers
- Where to place event handlers
- Executing code with event handlers
Event handlers
Event handlers are the way Javascript deals with events. Javascript contains a variety of event handlers for various purposes.
Javascript event handlers
-
onmouseover
This event handler is used when the mouse cursor is moved over an object.
-
onmouseout
This event handler is used when the mouse cursor is moved off an object.
-
onload
This event handler is used when an object has finished loading.
-
onclick
This even handler is used when an object is clicked.
-
onfocus
This event handler is used when an object is made active.
-
onselect
This event handler is used when the contents of an object are selected.
Where to place event handlers
Event handlers are placed inside HTML tags. You would place the appropriate event handler in the HTML tag that corresponds to the object you wish to effect. For example, you would place the onload event handler in the <body> tag for something to happen when a page has finished loading, or the onmouseout event handler in the <img> tag for something to happen when the mouse cursor is moved off an image.
Executing code with event handlers
Event handlers by themselves can not do anything. Some code has to be called for an event handler to execute. You can set event handlers to execute one or two or more individual lines of code or entire functions. When an event handler detects a particular event, it will execute the specified code or function.
Example:
<html> <script type="text/javascript"> function showMessage(){ alert("The textbox is now active"); } </script> <title>Javascript events</title> </head> <body> <form> <input type="button" value="Click here for a message" onclick="alert('Javascript is cool!');"> <br /><br /> <input type="text"Click here for another message size="30" onfocus="showMessage()" /> </form> </body> </html>
Output:
In the above examle, a button uses the onclick event handler to display the message "Javascript is cool!" in an alert box, and a textbox calls the function showMessage() when it is made active using the onfocus event handler. The showMessage() function displays the message "The textbox is now active" in an alert box.




