Game Development Reference
In-Depth Information
The page shown by the browser looks exactly the same as the first example (shown in Figure 1-2 ),
but there is a crucial difference between using JavaScript to do this as opposed to adding an attribute
to the body tag: the JavaScript script changes the color dynamically . This happens because the script
contains the following line:
document.addEventListener('DOMContentLoaded', changeBackgroundColor);
Inside a JavaScript application, you have access to all the elements in the HTML page. And
when things happen, you can instruct the browser to execute instructions. Here, you indicate that
changeBackgroundColor function should be executed when the page has finished loading.
There are many different types of these events in HTML and JavaScript. For example, you can add a
button to the HTML document and execute JavaScript instructions when the user clicks the button.
Here is an HTML document that illustrates this (see also Figure 1-5 ):
<!DOCTYPE html>
<html>
<head>
<title>BasicExample</title>
<script>
sayHello = function () {
alert("Hello World!");
}
document.addEventListener('click', sayHello);
</script>
</head>
<body>
<button>Click me</button>
</body>
</html>
Figure 1-5. An HTML page containing a button. When the user clicks the button, an alert is displayed
Search WWH ::




Custom Search