Where to-tutorial
When adding JavaScript to your webpage, you can place your code in different parts of the HTML file.
The most common places are:
JavaScript Between <script> Tags
JavaScript code must always be written inside the <script> and </script> tags.
Example:
JavaScript in the <body> Section
When you place you JavaScript inside the <body>, it usually runs when the browser reaches that part of the page.
You can also call a function using events like onclick on buttons.
Example:
Output
.webp)
On Clicking 'Enter' we get:
.webp)
JavaScript in the <head> Section
You can also define your JavaScript function inside the <head>.
This function will be available when the page loads, and you can call it from a button or any HTML element.
Example:
Output
.webp)
After Clicking 'Enter'
.webp)
For most interactive effects (like button clicks), defining the function in the <head> or placing scripts at the end of the <body> is best practice to ensure HTML elements are loaded first.
The most common places are:
- Inside the <head> section
- Inside the <body> section
JavaScript Between <script> Tags
JavaScript code must always be written inside the <script> and </script> tags.
Example:
<script>document.getElementById("demo").innerHTML = "Welcome to Quipoin!";</script>
JavaScript in the <body> Section
When you place you JavaScript inside the <body>, it usually runs when the browser reaches that part of the page.
You can also call a function using events like onclick on buttons.
Example:
<!DOCTYPE html><html>
<body>
<h2>Demo JavaScript in Body</h2>
<p id="demo">A sentence</p>
<button type="button" onclick="myFunction()">Enter</button>
<script> function myFunction() { document.getElementById("demo").innerHTML = "Sentence changed."; } </script>
</body>
</html>
Output
.webp)
On Clicking 'Enter' we get:
.webp)
JavaScript in the <head> Section
You can also define your JavaScript function inside the <head>.
This function will be available when the page loads, and you can call it from a button or any HTML element.
Example:
<!DOCTYPE html><html>
<head> <script> function myFunction() { document.getElementById("demo").innerHTML = "Changed sentence."; } </script></head>
<body>
<h2>Demo JavaScript in Head</h2>
<p id="demo">Sentence</p> <button type="button" onclick="myFunction()">Enter</button>
</body>
</html>
Output
.webp)
After Clicking 'Enter'
.webp)
Key Point
- JavaScript must be inside <script> tags.
- You can place scripts in the <head> or <body> depending on when you want the code to load.
- Functions placed in the <head> are available throughout the page.
- Code in the <body> is usually run after the HTML loads, making it common for interactive elements.
For most interactive effects (like button clicks), defining the function in the <head> or placing scripts at the end of the <body> is best practice to ensure HTML elements are loaded first.