JavaScript Code on HTML Page

Today I will show  how to write JavaScript code on HTML page:

All the JavaScript code you have to write in  HTML page. If you do not know HTML basic then you need to learn it first.

We can write JavaScript code anywhere in html page, but below steps are preferred to write the javascript code

  • In html <head>………script ………</head> section
  • In html <body>………script ………</ body > section
  • In html <head>………script ………</head> and <body>………script ………</ body > section
  • Script in External “.js” file and include in html head section
<!DOCTYPE HTML>
<html lang="en-US">
<head>
	<meta charset="UTF-8">
	<title>javascript</title>
	<script type="text/javascript"> //script in a html head section
		// JavaScript Code goes hear
	</script>
</head>
<body>
	<script type="text/javascript">  //script in a html body section
		// JavaScript Code goes Hear too
	</script>
</body>
</html>

// script include from external file  
<script src="example.js" type="text/javascript"></script>

If we want to write to the document by using a JavaScript we place the code in HTML body section

For create a JavaScript function and keep it for further use then we can use HTML head section or external .js file.

If  you want to use the same javascript in several pages or a single page then you can use external .js file to include in html page.

Example 1:

<!DOCTYPE HTML>
<html lang="en-US">
<head>
	<meta charset="UTF-8">
	<title>javascript</title>
</head>
<body>
	<script type="text/javascript">
		document.write("Hello World")
	</script>
</body>
</html>

Example 2:

<!DOCTYPE HTML>
<html lang="en-US">
<head>
	<meta charset="UTF-8">
	<title>javascript</title>
	<script type="text/javascript">
		function newfunction()	{
			document.write("Hello World");
		}
	</script>
	
</head>
<body>
	<script type="text/javascript">
		newfunction();
	</script>
</body>
</html>

Example 3:

Write in a simple text file and save it “file_name.js” extension:

Function my_func() {
	Document.write(“Hello World”);
}

In html head section include the js file like below

<!DOCTYPE HTML>
<html lang="en-US">
<head>
	<meta charset="UTF-8">
	<title>javascript</title>
<script src=" file_name.js" type="text/javascript"></script>
</head>
<body>
	<script type="text/javascript">
		new_function();
	</script>
</body>
</html>

Note: it is a good practice to ending a statement by putting semicolon “;”.