‘Hello JavaScript’
A basic understanding of html.
Resources:A list of various resources on JavaScript can be found here (XXX).
‘Hello JavaScript’ in a popup dialog
JavaScript is best known for making webpages more dynamic. The webbrowser loads the plain JavaScript code along with the html code and then executes it. Every webbrowser today allows to switch off execution of loaded JavaScript.
JavaScript code can be inserted in a lot of places within the html code. But the cleanest way is to define a <script> section within the html head.
JavaScript code can be embeded into the html text or it can be outsourced into another text file which then must be referenced in the html code.
That is all to know to code the first “Hello world!” example using JavaScript.
Create a html file with the following content:
<html> <head> <script type="text/javascript"> alert("Hello JavaScript, in a popup dialog!"); </script> </head> <body> </body> </html>
Whenloaded it in a web browser a popup dialog with the text “Hello JavaScript, in a popup dialog!” will be displayed.
The outsourced version of this example looks like the following. In the html file the script section is replaced by a script reference.
<html> <head> <script src="hello_js_dialog.js" type="text/javascript"></script> </head> <body> </body> </html>
And the JavaScript code is placed in the sepparated file named “hello_js_dialog.js”.
alert(“Hello JavaScript, in a popup dialog!”);
When loaded in a webbrowser it behaves exactly like the first example.
‘Hello JavaScript’ in modified html
JavaScript can be used to modify html code that is already loaded and processed by the webbrowser. When the html code is modified, the browser will re-render the page, thus displaying the changes.
The following example changes the text of a html tag:
<html> <head> </head> <body> <h1>Hello html!</h1> <p>Nice to meet you.</p> </body> <script type="text/javascript"> document.getElementsByTagName("h1")[0].firstChild.data="Hello JavaScript, in modified html!"; </script> </html>Note:
In this example the <script> section is inserted after the part of the html code it references to (the <h1> tag). This is because the webbrowser processes the html code line by line and tag by tag. Also JavaScript code is executed when the webbrowser runs over it. It does not first complete processing all the html code. If the script would be placed in the html head, like in the previous examples, the script would not be able to find the appropriate tag, as this tag was not yet processed by the webbrowser and the browser ‘has no knowledge of it’.