Showing posts with label JS code. Show all posts
Showing posts with label JS code. Show all posts

JavaScript code in HTML

Placement of JavaScript code in HTML

1) Script in <head> ..... </head> section.
2) Script in <body> .... <body> section.
3) Script in <body> ......</body and <head> ..... </head> sections.
4) Script in an external file and then include in <head>..... </head> section.

1) JavasScript in <head> .... </head Section:
   <html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
Click here for the result
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>

2) JavaScript in <body> ..... </body> section
<!DOCTYPE html>
<html>
<body>
<h1>My Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
   document.getElementById(
"demo").innerHTML = "Paragraph changed.";
}
</script>
</body>
</html>

3) JavaScript in <body> and <head> sections
<html>
<head>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<input type="button" onclick="sayHello()" value="Say Hello"/>
</body>
</html>


4). JavaScript in External file
    type the javaScript code in a seperate notepade file with saving as .js extension.
<html>
<head>
<script type="text/javascript" src="filename.js" ></script>
</head>
<body>
.......
</body>
</html>






Related Posts Plugin for WordPress, Blogger...