Events in Javascript
The absolute coolest thing about Javascript is the ability to create dynamic web
pages that increase user interaction, making the visitor feel like the website is almost
coming alive right before their eyes.
The building blocks of an interactive web page is the Javascript event system.
An event in Javascript is something that
happens with or on the web page. A few example of events:
- A mouse click
- The web page loading
- Mousing over a hot spot on the web page, also known as hovering
- Selecting an input box in an HTML form
- A keystroke
A Couple of Examples Using Events
Javascript has predefined names that cover numerous events that can occur, including
the ones listed above. To capture an event and make something happen when that event
occurs you must specify the event, the HTML element that will be waiting for the event,
and the function(s) that will be run when the event occurs.
We have used a Javascript event in a previous lesson, where we had an alert popup
when the button was clicked. This was an "onclick" Javascript event. We will do that
same example again, as well as the mouseover and mouseout events.
HTML & Javascript Code:
<html>
<head>
<script type="text/javascript">
<!--
function popup() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<input type="button" value="Click Me!" onclick="popup()"><br />
<a href="#" onmouseover="" onMouseout="popup()"">
Hover Me!</a>
</body>
</html>
Display:
With the button we used the event onClick event as our desired action and
told it to call our popup function that is defined in our header. To call a function
you must give the function name followed up with parenthesis "()".
Our mouseover and mouseout events were combined on one HTML element, a link. We wanted
to do nothing when someone put their mouse on the link, but when the mouse leaves (onMouseout) we displayed
a popup.
|