Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

10. Client-Side JavaScript > Embedding JavaScript in HTML

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 = displayTime;  
</script>
<style>         /* A CSS stylesheet for the clock */
#clock {        /* S....

  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free 10-Day Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint