HTML and CSS Reference
In-Depth Information
This tells the object to remove the listener from its list of listeners for that particular event, so it will not
receive further notifications.
Let's go ahead and see this in action. Start out with the skeleton document presented earlier, and add the
code to that:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Event Demo</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script>
window.onload = function () {
var canvas = document.getElementById('canvas');
canvas.addEventListener('mousedown', function (event) {
console.log("mouse down");
}, false);
canvas.addEventListener('mouseup', function (event) {
console.log("mouse up");
}, false);
};
</script>
</body>
</html>
In this example, first we accessed the canvas element (that has an id of 'canvas' ) through the DOM
interface using document.getElementById and stored it at the variable canvas . We then added listeners
for two events, mouseup and mousedown . As handlers, we passed in callback functions that are defined in-
line (remember, functions are objects that can be passed around), which print a message to the debugging
console. The handlers get passed an event object as an argument that contains some information about
the event; minimally, it contains the name of the event and information about what object triggered it. In the
case of mouse events, it contains information about the mouse location at the time of the event, which
mouse button was pressed (if any), and so on. For keyboard events, it would have information about what
keys were pressed at the time of the event.
Save this example as 02-event-demo.html. When you load the file in your web browser, you'll see that it
prints a message to the debugging console each time the mouse is pressed or released on the canvas
element. Make sure you get this exercise working, and the path to your CSS file is correct. It's a simple
exercise, but it's a good test to ensure your development environment is set up correctly.
If you are new to JavaScript and can get this example working and understand it, congratulations—you've
just moved from beginner up to intermediate status!
Now that you know a little bit more about handlers, you can get a better understanding of listeners. An
object generates an event, broadcasts that event, or notifies its listeners of the event. How does it do that
 
Search WWH ::




Custom Search