Tallaght Campus

Department of Computing

Javascript in HTML
To follow this tutorial, download and unzip this file bundle.

Part 1

Open the file js_in_html_1.html in a browser and in a text editor.
  1. The pop-up alert windows that appear when you load the js_in_html_1.html file in the browser are being created by some Javascript code. It can be found inside HTML script elements. What code causes the windows to pop up?
  2. Several alerts pop up. Examine the HTML file and explain what determines the order in which they pop up.
  3. From the way that the alert pop-ups interweave with the appearance of parts of the page, when do you think the code for creating the alerts is called?
  4. All the script elements in js_in_html_1.html are valid. What can you say about where in an HTML file script elements can be placed?
  5. Copy the following code into the head element of the HTML file.

    <style>
        script { display: block; color: red; } 
    </style>			

    Now load the page. What do you see? Why do you think the behaviour was different before?

  6. Do some detective work to find out where the last alert is being invoked. How does it differ from the other alerts?

Part 2

Open the file js_in_html_2.html in a browser and in a text editor.
  1. The Javascript statment alert("some string") is a call to a function (a piece of functionality) provided for our use by the browser, but we can define and use our own functions (pieces of functionality that we might like to reuse).

    In the HTML file js_in_html_2.html find callAlertHead and callAlertBody. These are two functions defined and used in the file (each function name appears in the file twice). How do we know the difference between a definition and a call (the use of a function)?

  2. What do the functions callAlertBody and callAlertHead do?
  3. Why is the second alert ("Hello from the BODY!") not appearing when you open the page in the browser?
  4. Find the definition of function callAlertBody and move it somewhere that will make the second alert pop up when the page is opened. Explain your solution.