Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JavaScript in heasd

JavaScript in <head> or <body>

Multiple scripts can be incorporated into an HTML document, positioned within either the <body> or <head> sections, or within both.

JavaScript in <head>

In this example, a JavaScript function is situated within the <head> section of an HTML page.

This function is triggered (called) upon clicking a button.

Example

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
  document.getElementById(“demo”).innerHTML = “Paragraph changed.”;
}
</script>
</head>
<body>

<h2>Demo JavaScript in Head</h2>

<p id=”demo”>A Paragraph</p>
<button type=”button” onclick=”myFunction()”>Try it</button>

</body>
</html>

JavaScript in <body>

In this example, a JavaScript function is located within the <body> section of an HTML page.

This function is triggered (called) upon clicking a button.

Example

<!DOCTYPE html>
<html>
<body>

<h2>Demo JavaScript in Body</h2>

<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>

Positioning scripts at the bottom of the <body> element enhances display speed, as script interpretation can delay rendering.