Skip to main content

JavaScript Basics in HTML — Adding Interactivity

The Three Layers of the Web

Just like a house:

LayerAnalogyRole
HTMLSkeleton & roomsStructure and content
CSSPaint, furniture, curtainsVisual appearance
JSLight switches, doorbells, thermostatsInteractivity 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

AttributeParsingExecutionUse Case
(none)Blocks parserImmediately when downloadedLegacy code
deferContinues in parallelAfter parsing complete ✅Most scripts
asyncContinues in parallelAs soon as downloadedAnalytics, 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>
<button id="myBtn">Click Me</button>

<script>
const btn = document.getElementById('myBtn');
btn.addEventListener('click', function() {
alert('Button was clicked!');
});
</script>

Common Events

EventTrigger
clickElement clicked
mouseoverMouse enters element
mouseoutMouse leaves element
keydownKey pressed
submitForm submitted
loadPage 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>


Key Takeaways

ConceptSummary
<script> tagEmbeds or links JavaScript in HTML
deferDownloads in parallel, runs after parse
asyncDownloads in parallel, runs when ready
DOMTree representation of HTML document
SelectiongetElementById, querySelector, querySelectorAll
ManipulationinnerText, innerHTML, style
EventsaddEventListener for handling interactions
Placement<head> with defer or end of <body>