Part 1
Open the file js_in_html_1.html in a browser and in a text editor.-
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?
alert("some text")
-
Several alerts pop up. Examine the HTML file and explain what determines the order in which they pop up.
The order in which they appear in the file is the order in which they pop up.
-
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?
In some browsers, the alerts block the loading of the visible content. In newer browsers this is not the case.
-
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?
Anywhere.
-
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?
By default, script elements are not visible, however, if a visible style (e.g. display: block) is explicitly specified for the script element type, script elements will be displayed in the page.
-
Do some detective work to find out where the last alert is being invoked. How does it differ from the other alerts?
It is being invoked from an external file, js_in_html_1.js.
Part 2
Open the file js_in_html_2.html in a browser and in a text editor.-
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)?
There is a difference in syntax, which for a function definition is:function <the function name>() { <some code, constituting the function body> }
The syntax of a function call is:<the function name>();
NOTE: The examples above are for a function without parameters. -
What do the functions callAlertBody and callAlertHead do?
They both simply call the alert function, each passing in text corresponding to its name.
-
Why is the second alert ("Hello from the BODY!") not appearing when you open the page in the browser?
Because the call is made before the function is defined in the file.
-
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.
It can be moved to any position that will be parsed before the call, e.g. inside the head element of the document.