O'Reilly logo

JavaScript Pocket Reference, 3rd Edition by David Flanagan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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. window.onload ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required