Locked lesson.
About this lesson
What is an event, and what can you do with it?
Exercise files
Download this lesson’s related exercise files.
Understanding Events.docx59.1 KB Understanding Events - Solution.docx
59.4 KB
Quick reference
Understanding Events
Events are what people often think of when they think of JavaScript.
When to use
Anytime you want to allow the user to interact with the page - clicking on things, mousing over, etc - use events.
Instructions
There are many JavaScript events. Several popular ones are:
onclick
onload
onchange
onmouseover
onmouseout
To use onclick:
<h1 onclick="this.innerHTML = 'Goodbye World'">Hello World!</h1>
To use onclick to call a function:
<script>
function myFunction(id) {id.innerHTML = "ha!";}
</script>
To use onload:
<head>
<script>
function popup(){alert("My popup message");}
</script>
</head>
<body onload="popup()">
To use onchange:
<head>
<script>
function upperCase(){
var field = document.getElementById("name");
field.value = field.value.toUpperCase();
}
</script>
</head>
Enter Your Name: <input type="text" id="name" onchange="upperCase()>
To use mouseOver:
<p id="first" onmouseover="mOver(this)" onmouseout="mOut(this)">This is some text...</p>
<script>
function mOver(thing) { thing.innerHTML = "Mouse Over";}
function mOut(thing) {thing.innerHTML = "This is some text...";}
</script>
Hints & tips
- There are lots of JavaScript events
- Use them when you want some user interaction on a web page
Lesson notes are only available for subscribers.