JavaScript: Where To?
JavaScript code can be added to HTML files in multiple ways. It can be placed directly within the HTML file or included as an external file. Understanding where to place JavaScript is crucial for structuring your projects effectively.
Key Topics
Inline JavaScript
Inline JavaScript is written directly within an HTML element's attribute, such as onclick
, onmouseover
, etc. It is suitable for simple, one-time-use scripts.
<button onclick="alert('Hello, this is inline JavaScript!')">Click Me</button>
Output
Clicking the button displays an alert with the message: "Hello, this is inline JavaScript!"
Internal JavaScript
Internal JavaScript is placed within the <script>
tags inside the HTML file. It is used for scripts specific to a single HTML file.
<!DOCTYPE html>
<html>
<head>
<title>Internal JavaScript</title>
<script>
function showAlert() {
alert('Hello from internal JavaScript!');
}
</script>
</head>
<body>
<button onclick="showAlert()">Click Me</button>
</body>
</html>
Output
Clicking the button displays an alert with the message: "Hello from internal JavaScript!"
External JavaScript
External JavaScript is written in a separate .js
file and linked to the HTML using the <script>
tag. It is ideal for reusability and maintaining cleaner HTML files.
<!DOCTYPE html>
<html>
<head>
<title>External JavaScript</title>
<script src="script.js"></script>
</head>
<body>
<button onclick="externalFunction()">Click Me</button>
</body>
</html>
// script.js
function externalFunction() {
alert('Hello from external JavaScript!');
}
Output
Clicking the button displays an alert with the message: "Hello from external JavaScript!"
DOM Interaction Example
Below is an example of JavaScript interacting with the DOM, demonstrating the placement of external JavaScript files for dynamic content manipulation.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DOM Example</title>
<script src="domScript.js"></script>
</head>
<body>
<button id="changeColor">Change Color</button>
<div id="colorBox" style="width: 100px; height: 100px; background-color: lightblue; margin-top: 10px;"></div>
</body>
</html>
// domScript.js
document.getElementById('changeColor').addEventListener('click', () => {
const box = document.getElementById('colorBox');
box.style.backgroundColor = box.style.backgroundColor === 'lightblue' ? 'lightgreen' : 'lightblue';
});
Explanation: This example demonstrates using external JavaScript for DOM manipulation. Clicking the button toggles the box's color between light blue and light green.
Key Takeaways
- Inline JavaScript: Simple, but harder to maintain for larger applications.
- Internal JavaScript: Suitable for single HTML files.
- External JavaScript: Encourages code reusability and cleaner HTML.
- Dynamic Interaction: JavaScript can manipulate HTML elements and styles dynamically.