JavaScript Basics in HTML — Adding Interactivity
The Three Layers of the Web
Just like a house:
| Layer | Analogy | Role |
|---|---|---|
| HTML | Skeleton & rooms | Structure and content |
| CSS | Paint, furniture, curtains | Visual appearance |
| JS | Light switches, doorbells, thermostats | Interactivity and behavior |
The <script> Tag
Inline JavaScript
Add JavaScript directly inside a <script> tag.
<script>
alert('Hello, world!');
</script>
External JavaScript
Link to a separate .js file:
<script src="app.js"></script>
// app.js
alert('Hello from an external file!');
Script Loading: defer vs async
| Attribute | Parsing | Execution | Use Case |
|---|---|---|---|
| (none) | Blocks parser | Immediately when downloaded | Legacy code |
defer | Continues in parallel | After parsing complete ✅ | Most scripts |
async | Continues in parallel | As soon as downloaded | Analytics, ads |
<!-- Blocks rendering — avoid -->
<script src="slow.js"></script>
<!-- Defers execution — recommended -->
<script src="app.js" defer></script>
<!-- Async — independent scripts -->
<script src="analytics.js" async></script>
Where to Place Scripts
❌ Old way — end of <body>
<body>
<!-- ... all HTML ... -->
<script src="app.js"></script>
</body>
✅ Modern way — <head> with defer
<head>
<script src="app.js" defer></script>
</head>
<body>
<!-- ... all HTML ... -->
</body>
With defer, the script downloads in the background and runs only after the HTML is fully parsed. No need to put scripts at the bottom.
The DOM — Document Object Model
When the browser loads HTML, it creates a tree structure called the DOM.
JavaScript can read, modify, add, or remove any node in this tree — that's DOM manipulation.
Simple DOM Manipulation
Selecting Elements
// By ID
const title = document.getElementById('main-title');
// By CSS selector (returns first match)
const firstParagraph = document.querySelector('p');
// By class (returns all matches)
const cards = document.querySelectorAll('.card');
Reading and Writing Content
const heading = document.getElementById('heading');
heading.innerText = 'New Text!'; // plain text
heading.innerHTML = '<em>New HTML!</em>'; // HTML content
Changing Styles
const box = document.getElementById('box');
box.style.color = 'blue';
box.style.backgroundColor = '#f0f0f0';
box.style.fontSize = '20px';
Event Handling
onclick Attribute (inline)
<button onclick="alert('Clicked!')">Click Me</button>
addEventListener (recommended)
<button id="myBtn">Click Me</button>
<script>
const btn = document.getElementById('myBtn');
btn.addEventListener('click', function() {
alert('Button was clicked!');
});
</script>
Common Events
| Event | Trigger |
|---|---|
click | Element clicked |
mouseover | Mouse enters element |
mouseout | Mouse leaves element |
keydown | Key pressed |
submit | Form submitted |
load | Page finished loading |
Try It Yourself
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
padding: 50px;
}
#message {
font-size: 24px;
margin: 20px 0;
padding: 15px;
background-color: #f0f0f0;
border-radius: 8px;
}
button {
font-size: 18px;
padding: 10px 25px;
border: none;
border-radius: 5px;
background-color: #007bff;
color: white;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
</style>
</head>
<body>
<h1>Interactive Page</h1>
<div id="message">Click the button to change this text.</div>
<button id="changeBtn">Change Text</button>
<button id="resetBtn">Reset</button>
<script>
const message = document.getElementById('message');
const changeBtn = document.getElementById('changeBtn');
const resetBtn = document.getElementById('resetBtn');
changeBtn.addEventListener('click', function() {
message.innerText = 'You clicked the button! 🎉';
message.style.backgroundColor = '#d4edda';
message.style.color = '#155724';
});
resetBtn.addEventListener('click', function() {
message.innerText = 'Click the button to change this text.';
message.style.backgroundColor = '#f0f0f0';
message.style.color = '#000';
});
</script>
</body>
</html>
🔗 Related Topics
- CSS in HTML — Style elements with CSS
- Form Validation — Dynamic validation with JavaScript
- Web Components — Build reusable custom elements
Key Takeaways
| Concept | Summary |
|---|---|
<script> tag | Embeds or links JavaScript in HTML |
defer | Downloads in parallel, runs after parse |
async | Downloads in parallel, runs when ready |
| DOM | Tree representation of HTML document |
| Selection | getElementById, querySelector, querySelectorAll |
| Manipulation | innerText, innerHTML, style |
| Events | addEventListener for handling interactions |
| Placement | <head> with defer or end of <body> |