Chapter 10. Client-Side JavaScript

The first part of this book described the core JavaScript language. We now move on to JavaScript as used within web browsers, commonly called client-side JavaScript. Most of the examples we’ve seen so far, while legal JavaScript code, have no particular context; they are JavaScript fragments that run in no specified environment. This chapter introduces that context, and the chapters that follow fill in the details.

Embedding JavaScript in HTML

JavaScript code can appear inline within an HTML file between <script> and </script> tags:

<script>
// Your JavaScript code goes here
</script>

Example 10-1 is an HTML file that includes a simple JavaScript program. The comments explain what the program does, but the main point of this example is to demonstrate how JavaScript code is embedded within an HTML file along with, in this case, a CSS stylesheet.

Example 10-1. A simple JavaScript digital clock

<!DOCTYPE html> <!-- This is an HTML5 file --> <html> <!-- The root element --> <head> <!-- Title, scripts & styles go here --> <title>Digital Clock</title> <script> // A script of js code // Define a function to display the current time function displayTime() { var now = new Date(); // Get current time // Find element with id="clock" var elt = document.getElementById("clock"); // Display the time in the element elt.innerHTML = now.toLocaleTimeString(); // And repeat in one second setTimeout(displayTime, 1000); } // Start the clock when the document loads. ...

Get JavaScript Pocket Reference, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.