WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

JavaScript Where To


The script in must be located <script> versus</script> Between tags
Scripts can be placed in HTML pages <body> with <head>Section.

The <script> Tag

To insert in an HTML page JavaScript´╝îplease use <script> tag

<script> with </script> Will tell JavaScript where to start and end.

<script> with </script> The line of code between contains JavaScript:

Example

<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>

JavaScript functions and events

The JavaScript statement in the above example is executed when the page loads.

Usually, we need to execute code when an event occurs, such as when the user clicks a button.

If we put JavaScript code in a function, we can call the function when an event occurs.

You will learn more about JavaScript functions and events in later chapters.

in <head> or <body> JavaScript

You can put an unlimited number of scripts in your HTML document.

Scripts can be placed in HTML <body> or <head> Part, or both parts.

The usual way is to put the function in <head> Section, or at the bottom of the page. This way they can be placed in the same place without disturbing the content of the page.


JavaScript in <head>

In this example, we place a JavaScript function on the HTML page <head> section.

This function will be called when the button is clicked:

Example

<!DOCTYPE html>
<html>

<head>
<script>
function myFunction () { document.getElementById ("demo"). innerHTML = "My first JavaScript function"; }
</script>
</head>

<body>

<h1>My Web Page</h1>

<p id="demo">A Paragraph</p>

<button type="button" onclick="myFunction()">Try it</button>

</body>
</html>

Try it Yourself »

JavaScript in <body>

In this example, we place a JavaScript function on the HTML page <body> section.

This function will be called when the button is clicked:

Example

<!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>
Try it Yourself »

External JavaScript

You can also save the script to an external file. External files often contain code used by multiple web pages.

External JavaScript files have the file extension .js.

To use external files, <script> Set the .js file in the "src" attribute of the tag:

Example

<!DOCTYPE html>
<html>
<body>
<script src="myScript.js"></script>
</body>
</html>
Try it yourself »

External JavaScript Advantages

You can also save the script to an external file. External files often contain code used by multiple web pages.

External JavaScript files have the file extension .js.

To use external files, <script>Set the .js file in the "src" attribute of the tag: