Monday, February 1, 2010

how & where

Tags


In order to use Javascript, the script code must be enclosed between the following two tags:
<script type="text/Javascript">
</script>


HTML tags inside JavaScript


JavaScript allows HTML tags to be added within it.
<html>
<body>
<script type="text/Javascript>
document.write("<h1>"Hello World!"</h1>");
</script>

</body>
</html>


Handling Simple Browsers


Browsers that do not support JavaScript, will display JavaScript as page content. To prevent them from doing this, and as part of the JavaScript standard, the HTML comment tag should be used to "hide" the Javascript as follows:
<html>
<body>
<script type="text/javascript">
<!--
document.write("Hello World!");
//-->
</script>

</body>
</html>


Where to Put the JavaScript

  • JavaScripts in the body section will be executed WHILE the page loads.
  • JavaScripts in the head section will be executed when CALLED.


Scripts in <head>

Scripts to be executed when they are called, or when an event is triggered, go in head section. Example:
<head>
<script type="text/javascript">
function message()
{
alert("This alert box was called with the onload event"):
}
</script>

</head>

<body onload="message()">
</body>
The alert() function will generate an alert box, when the html page is loaded.


Scripts in <body>

Scripts to be executed when the page loads go in the body section.

Unlimited Scripts

You can place an unlimited number of scripts in your document, so you can have scripts in both the body and the head section.

External JavaScript

If you want to run the same JavaScript on several pages, without having to write the same script on every page, you can write a JavaScript in an external file.

Save the external JavaScript file with a .js file extension. Example:
<head>
<script type="text/javascript" src="xxx.js"></script>
</head>



link

No comments:

Post a Comment