Archive for JavaScript

How to use JavaScript in HTML page

Thursday, April 16th, 2009

JavaScript is a dynamic programming language. It can use for dynamic content. JavaScript can use with html page inside <body> tag and inside of <script> tag in <head> tags.

JavaScript code can be written on separate JS file. This JS file can be included in html page. It is a good practice of programming to keep everything separate. In JavaScript, we can make functions and global code. Functions can be fired by explicit events. These events are onClick, onFocus, onBlur onMouseOver.

Important thing is JavaScript and HTML both execute at browser. Output will come at same time.

We are going to add JavaScript code. See how to use JavaScript in HTML page by example.

1. Where can add JavaScript

2. Run JavaScript code automatically

3. Display text string in JavaScript.

Where to add JavaScript

Head tags with code

<html>
<head>
<title>How to use JavaScript in HTML page </title>
<script>
function alertMe()
{
    alert("This is javascript code");
}
</script>

</head>

Include JS file

<html>
<head>
<title>Include JavaScript in HTML page </title>
<script src="include.js"></script>

</head>

Code in body tag

</head>

<body>
<script>
   var str="This is javascript variable";
   alert(str);
</script>
</body>
</html>

Run JavaScript code automatically

JavaScript code inside body tag run automatically

<html>
<head>
<title>Run JavaScript code automatically</title>
</head>

<body>
<script>
   var str="This is javascript variable";
   alert(str);
</script>
</body>
</html>

Display text string in JavaScript

<html>
<head>
<title>Display JavaScript code</title>
</head>

<body>
<script>
   var str="This is javascript variable";
   document.write(str);
</script>
</body>
</html>