In JavaScript, we treat events made by users as an input, and we manipulate the DOM structure as an output. Most of the time in games/animations, we will change state variables of moving objects, such as position or speed of an alien ship, and the animation loop will take care of these variables to move the objects.
The events are called DOM events, and we use the DOM JavaScript API to create event handlers.
You will often find this in examples on the Web:
document.getElementById('someDiv').onclick = function(evt) {
alert('clicked!');
}
This method is fine, but you will not be able to attach several listener functions. If you need to do this, the preferred version is the next one.
This is how we do it:
document.getElementById('someDiv').addEventListener('click', function(evt) {
alert('clicked!');
}, false);
The third parameter is not important for now, just set it to false, or simply do not add a third parameter.
When you create an EventListener and attach it to an element, an event object will be passed as a parameter to your callback, just like this:
element.addEventListener('click', function(event) {
// now you can use the event object inside the callback
}, false);
Depending on the type of event you are listening to, we will use different properties from the event object in order to get useful information like: "what keys have been pressed down?", "what is the position of the mouse cursor?", "which mouse button is down?", etc.
Let's see next how to deal with the keyboard and the mouse. In the W3Cx HTML5 Apps and Games course, we look at additional APIs such as the gamePad API for using USB or wireless gamepads/joysticks/game controllers.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Click on button</title>
</head>
<body>
<button id="myButton">Click me!</button>
<script>
var button = document.getElementById('myButton');
// Define a click listener on the button
button.addEventListener('click', processClick);
// callback
function processClick(event) {
console.log("Button clicked");
// What is the event parameter?
}
</script>
</body>
</html>