Adding JavaScript to html

Where should the JavaScript be placed inside a html page?

JavaScript code can be placed inside <script> and </script> tags. The script tags can go anywhere in <body> or <head> section of HTML page.

Using <script> Tag

JavaScript code must be inside <script></script> tags to translate. Anything outside of <script> tag is
taken as normal HTML code and not execute as a JavaScript code.

Example

<html>
	<body>
		<p id="div_id">A Paragraph</p>
		<button type="button" onclick="myFunction()">Try it</button>
		<script>
		function myFunction() {
			document.getElementById("div_id").innerHTML = "Content changed.";
		}
		</script>
		<h1>My Web Page</h1>
	</body>
</html>

Download the code Run the code

JavaScript inside <head> or <body> tag

You can place unlimited number of scripts in an HTML page. Scripts code can be placed anywhere between <head> tag or <body> tag or both.

Inside <head>

In below example, JavaScript code is written within <head> section of page. The function is called when a someone click on the button

Example

<html>
	<head>
		<script>
		function myFunction() {
			document.getElementById("div_id").innerHTML = "Content changed.";
		}
		</script>
	</head>
	<body>
		<h1>My Web Page</h1>
		<p id="div_id">A Paragraph</p>
		<button type="button" onclick="myFunction()">Try it</button>
	</body>
</html>

Download the code Run the code

Inside <body>

In below example, JavaScript code is written within <body> section of page. The function is called when a someone click on the button

Example

<!DOCTYPE html>
<html>
	<body>
		<p id="demo">Welcome to Javascript</p>
		
		<script>
		document.getElementById("demo").innerHTML = "My First JavaScript code";
		</script>
	</body>
</html>

Download the code Run the code
It is a best practice to place scripts at the bottom of the page, just before </body> tag. This will improve page load time. Otherwise  JavaScript code execution will halt the page rendering,  until it is fully done.

Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .