Friday 1 April 2011

How to


The HTML <script> tag is used to insert a JavaScript into an HTML page.

Writing to The HTML Document

The example below writes a <p> element with current date information to the HTML document:

Example

<html>
<body>

<h1>My First Web Page</h1>

<script type="text/javascript">
document.write("<p>" + Date() + "</p>");
</script>


</body>
</html>
Note: Try to avoid using document.write() in real life JavaScript code. The entire HTML page will be overwritten if document.write() is used inside a function, or after the page is loaded. However, document.write() is an easy way to demonstrate JavaScript output in a tutorial.

Changing HTML Elements

The example below writes the current date into an existing <p> element:

Example

<html>
<body>

<h1>My First Web Page</h1>

<p id="demo"></p>

<script type="text/javascript">
document.getElementById("demo").innerHTML=Date();
</script>


</body>
</html>
Note: To manipulate HTML elements JavaScript uses the DOM method getElementById(). This method access the element with the specified id.

Examples Explained

To insert a JavaScript into an HTML page, use the <script> tag.
Inside the <script> tag use the type attribute to define the scripting language.
The <script> and </script> tells where the JavaScript starts and ends:
<html>
<body>
<h1>My First Web Page</h1>

<p id="demo">This is a paragraph.</p>

<script type="text/javascript">
... some JavaScript code ...
</script>
</body>
</html>
The lines between the <script> and </script> contains the JavaScript and are executed by the browser.
In this case the browser will replace the content of the HTML element with id="demo", with the current date:
<html>
<body>
<h1>My First Web Page</h1>

<p id="demo">This is a paragraph.</p>

<script type="text/javascript">
document.getElementById("demo").innerHTML=Date();
</script>
</body>
</html>
Without the <script> tag(s), the browser will treat "document.getElementById("demo").innerHTML=Date();" as pure text and just write it to the page.

Some Browsers do Not Support JavaScript

Browsers that do not support JavaScript, will display JavaScript as page content.
To prevent them from doing this, and as a part of the JavaScript standard, the HTML comment tag should be used to "hide" the JavaScript.
Just add an HTML comment tag <!-- before the first JavaScript statement, and a --> (end of comment) after the last JavaScript statement, like this:
<html>
<body>
<script type="text/javascript">
<!--
document.getElementById("demo").innerHTML=Date();
//-->
</script>
</body>
</html>
The two forward slashes at the end of comment line (//) is the JavaScript comment symbol. This prevents JavaScript from executing the --> tag.

No comments:

Post a Comment