WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

JavaScript Where To


JavaScript can be put in the <body> and the <head> segments of a HTML page.


The <script> Tag

In HTML, JavaScript code must be embedded among <script> and </script> tags.

Example

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

JavaScript Functions and Events

A JavaScript function is a square of JavaScript code, that can be executed when "asked" for.

For model, a capacity can be executed when a event happens, similar to when the client clicks a button.

You will adapt substantially more about capacities and occasions in later chapters.


JavaScript in <head> or <body>

You can put any number of contents in a HTML document.

Scripts can be put in the <body>, or in the <head> area of a HTML page, or in both.


JavaScript in <head>

In this model, a JavaScript work is set in the <head> area of a HTML page.

The work is summoned (called) when a catch is clicked:

Example

<!DOCTYPE html>
<html>

<head>
<script>
work myFunction() {
    document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</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 precedent, a JavaScript work is put in the <body> segment of a HTML page.

The work is conjured (called) when a catch 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>
work myFunction() {
   document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>

</body>
</html>
Try it Yourself »

External JavaScript

Scripts can likewise be set in outside files.

External contents are commonsense when a similar code is utilized in a wide range of pages.

JavaScript documents have the file augmentation .js.

To utilize an outside content, put the name of the content record in the src (source) quality of the <script> tag:

Example

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

External JavaScript Advantages

Placing JavaScripts in external files has some advantages:

  • It separates HTML and code
  • It makes HTML and JavaScript easier to read and maintain
  • Cached JavaScript files can speed up page loads