Javascript
JS intro
JS basics
JS variables
JS functions
JS popup boxes
JS conditional logic
JS loops
JS arrays
JS objects
JS strings
JS events
JS errors
JS DOM
JS elements
JS new windows
JS date and time
JS cookies
JS print
JS redirect
JS void 0
JS Summary

Programming

Programming intro
Java

Markup

First webpage guide
HTML
XHTML

Style & Layout

CSS

Browser scripting

VBScript
AJAX

Server scripting

PHP
ASP

Making money online

Make money online

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

Event handlers are the way Javascript deals with events. Javascript contains a variety of event handlers for various purposes.

Javascript event handlers

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.

Practice

Online code editor
Practical examples
Practical exercises
Step-by-step tutorials

Reference

Terms glossary
Reference material

Rate this site

Rate this site
Visitor comments