Home » JavaScript

Where to place JavaScript Code?

In this article, we are going to learn about the placement of the JavaScript code, where can we place the JavaScript code in an HTML file?
Submitted by IncludeHelp, on March 02, 2019

In an HTML code, JavaScript can be placed at three places...

  1. Between the <head>...</head> tag
  2. Between the <body>...</body> tag
  3. In the external file with an extension ".js"

Between the <head>...</head> and <body>...</body> tags

If we want to place a JavaScript code in an HTML file, we can place either in <head>...</head> tag or <body>...</body> tag.

Syntax:

<script type="text/javascript">
        //js code
</script>

Example:

<html>
<head>
	<title>JavaScipt Example</title>
	<script type="text/javascript">
		//function to add two numbers
		function sum(a, b){
			return (a+b);
		}
	</script>
</head>

<body>
	<script type="text/javascript">
		//function to subtract two numbers
		function sub(a, b){
			return (a-b);
		}
	</script>
	<p>Here, we are printing sum & sum...</p>
	<p id="result1"></p>
	<p id="result2"></p>

	<script type="text/javascript">
		//calling functions & printing the values
		document.getElementById("result1").innerHTML = "sum = " + sum(10,20);
		document.getElementById("result2").innerHTML = "sub = " + sub(10,20);
	</script>	
</body>
</html>

Output:

Here, we are printing sum & sum...

sum = 30

sub = -10

In the external file with an extension ".js"

We can also write JavaScript code in an external file, and import the file in an HTML file.

Syntax to import JavaScript file in an HTML file:

    <script src="file_name.js"></script>

Example:

JavaScript file (functions.js)

//function to add two numbers
function sum(a, b){
	return (a+b);
}

//function to subtract two numbers
function sub(a, b){
	return (a-b);
}

HTML file

<html>
<head>
	<title>JavaScipt Example</title>
	<script src="functions.js"></script>
</head>

<body>
	<p>Here, we are printing sum & sum...</p>
	<p id="result1"></p>
	<p id="result2"></p>

	<script type="text/javascript">
		//calling functions & printing the values
		document.getElementById("result1").innerHTML = "sum = " + sum(10,20);
		document.getElementById("result2").innerHTML = "sub = " + sub(10,20);
	</script>	
</body>
</html>

Output:

Here, we are printing sum & sum...

sum = 30

sub = -10





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.