spacer.png, 0 kB
spacer.png, 0 kB
Home arrow Javascript arrow Javascript code on your HTML pages
Javascript code on your HTML pages PDF Print E-mail
 
There are several ways to include Javascript code in your HTML pages taking advantage of this browser technology.

The first method is to include the code directly in the HTML page with the <SCRIPT> tag. Your code will be executed once the HTML page has been parsed by the browser.
<script type="text/javascript">
  window.alert("Javascript");
</script>
It's common sometimes to see the code enclosed in HTML comment <!-- --> just after the <script> tag.
This method is outdated and was used for non javascript capable browser. Today these browser recognize the <script> tag skipping everything is inside.

A second method to use Javascript code is to include an external file (useful in case the same code have to be reused). The Javascript file enclosed will have no <SCRIPT> tag. This one will be present instead in the HTML source as per the below example:
<script language="Javascript" type="text/javascript" src="script.js"></script>
The SRC attribute has the script URL whose address could also be in an external server.

Another way for javascript is to dinamically load the code when the page is executed (useful for example upon a user request).
The document.write() function is not the best compatible solution for all the browsers. Follow then the below example:
<html>
<head>
<title>Prova Javascript</title>
</head>
<body>
<script language="Javascript" type="text/javascript">
  var s = document.createElement("script");
  s.setAttribute("type","text/javascript");
  s.setAttribute("language","JavaScript";
  s.setAttribute("src","script.js");
  document.getElementByTagName("head")[0].appendChild(s);
</script>
</body>
</html>
 
It's possible to include Javascript code also with a pseudo URL, such as the following example
<a href="javascript:window.alert('Javascript');">click here</a>
if the code enclosed in the URL (that could belong also to a IMG or CSS HTML tag also) returns a value this one is then printed. To avoid this you can use the special javascript:void(codice) function.
 
It's possible also to execute code together with Javascript events.
Most of HTML elements handle events: here below the <body> tag case
<html>
<head>
<title>Javascript</title>
<script language="Javascript" type="text/javascript">
function showText() {
  window.alert("Javascript");
}
</script>
</head>
<body onload="showText();">
</body>
</html>
 
For the users that have Javascript disabled (from the statistics around 10% of them for safety, business policy or other reasons) we should provide a solution too.
Have a look then at the code below (with the <noscript> tag). 
<script type="text/javascript">
  document.write("Javascript");
</script>
<noscript>
  Javascript disabled
</noscript>
Last Updated ( mercoledì, 28 novembre 2007 )
 
< Prev   Next >
spacer.png, 0 kB
spacer.png, 0 kB
spacer.png, 0 kB