JavaScript is the programming language of the web. While HTML provides structure and CSS provides styling, JavaScript adds interactivity and dynamic behavior to web pages. JavaScript can be embedded directly in HTML using the <script> element or linked from external files.
Adding JavaScript to HTML
Inline JavaScript
JavaScript can be written directly inside a HTML elements. That is what we called inline Javascript.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript Example</title>
</head>
<body>
<h1>My Web Page</h1>
<button onclick="alert('Hello, World!')">Click Me</button>
</body>
</html>
Internal JavaScript
Internal JavaScript is JavaScript that is written inside the <script> element in the <head> or <body> section of the HTML file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript Example</title>
</head>
<body>
<h1>My Web Page</h1>
<script>
// JavaScript code here
console.log('Hello, World!');
</script>
</body>
</html>
External JavaScript File
Better practice is to link to an external JavaScript file:
<!-- HTML file -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript Example</title>
<script src="script.js"></script>
</head>
<body>
<h1>My Web Page</h1>
<button id="myButton">Click Me</button>
</body>
</html>
// script.js file
document.addEventListener('DOMContentLoaded', function() {
const button = document.getElementById('myButton');
button.addEventListener('click', function() {
alert('Hello, World!');
});
});
The reason we said its best practice to use external JavaScript files is that it separates the structure (HTML) from the behavior (JavaScript), making the code more maintainable and reusable.
Script Tag Attributes
Common Attributes
The script tag can have several attributes to control how the script is loaded and executed.
<!-- Basic script tag -->
<script src="script.js"></script>
<!-- With type attribute -->
<script type="text/javascript" src="script.js"></script>
<!-- Async loading (non-blocking) -->
<script src="script.js" async></script>
<!-- Deferred loading (executes after DOM parsing) -->
<script src="script.js" defer></script>
<!-- Inline script with defer -->
<script defer>
console.log('This script is deferred');
</script>
Loading Performance
Modern web development emphasizes non-blocking script loading to improve page performance.
<!-- Traditional blocking script -->
<script src="analytics.js"></script>
<!-- Modern non-blocking scripts -->
<script src="analytics.js" async></script>
<script src="main.js" defer></script>
<!-- Module script (ES6 modules) -->
<script type="module" src="module.js"></script>
<!-- Nomodule script for older browsers -->
<script nomodule src="legacy.js"></script>
Script Placement
The placement of script tags in your HTML can affect page loading performance and execution order.
Head vs Body
Scripts in the head tag are loaded before the page content, while scripts in the body tag are loaded after the content.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Script Placement</title>
<!-- Scripts in head (with defer) -->
<script src="app.js" defer></script>
</head>
<body>
<h1>My Web Page</h1>
<p>Content here</p>
<!-- Scripts at end of body -->
<script src="analytics.js"></script>
<script>
// Inline script at end of body
console.log('Page ready');
</script>
</body>
</html>
Most of the develpers recommend placing script tags at the end of the body tag to improve page loading performance.
JavaScript and HTML Elements
JavaScript can interact with HTML elements to create dynamic and interactive web pages.
DOM Manipulation
The Document Object Model (DOM) is a tree-like structure that represents the HTML document. JavaScript can manipulate the DOM to change the content, structure, and style of HTML elements.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>DOM Manipulation</title>
</head>
<body>
<h1 id="title">Original Title</h1>
<p id="content">Original content</p>
<button id="changeBtn">Change Content</button>
<script>
// Select elements
const title = document.getElementById('title');
const content = document.getElementById('content');
const button = document.getElementById('changeBtn');
// Add event listener
button.addEventListener('click', function() {
// Change text content
title.textContent = 'New Title';
content.innerHTML = '<strong>New content</strong> with <em>formatting</em>';
// Change styles
title.style.color = 'blue';
content.style.backgroundColor = 'yellow';
// Add CSS class
title.classList.add('highlight');
});
</script>
</body>
</html>
As you can see we use DOM to change the content, style, and structure of HTML elements. We will learn more about it in Javascript section.
Creating Elements
JavaScript can create new HTML elements and add them to the DOM.
<body>
<div id="container"></div>
<button id="addElement">Add Element</button>
<script>
const container = document.getElementById('container');
const addButton = document.getElementById('addElement');
addButton.addEventListener('click', function() {
// Create new element
const newDiv = document.createElement('div');
newDiv.textContent = 'New element added!';
newDiv.className = 'new-element';
newDiv.style.padding = '10px';
newDiv.style.margin = '5px 0';
newDiv.style.backgroundColor = '#e8f4fd';
newDiv.style.border = '1px solid #bee5eb';
newDiv.style.borderRadius = '4px';
// Add to container
container.appendChild(newDiv);
});
</script>
</body>
Event Handling
Event handling allows JavaScript to respond to user interactions like clicks, key presses, and form submissions.
Common Events
Here are some common events that can be handled with JavaScript:
<body>
<!-- Click events -->
<button id="clickBtn">Click Me</button>
<div id="clickArea" style="width: 200px; height: 100px; background-color: lightblue; padding: 20px; margin: 10px 0;">
Click this area
</div>
<!-- Form events -->
<form id="myForm">
<input type="text" id="textInput" placeholder="Type here">
<button type="submit">Submit</button>
</form>
<!-- Keyboard and mouse events -->
<input type="text" id="keyInput" placeholder="Press keys here">
<div id="mouseArea" style="width: 300px; height: 200px; background-color: lightgreen; padding: 20px; margin: 10px 0;">
Mouse over me
</div>
<script>
// Click events
document.getElementById('clickBtn').addEventListener('click', function() {
alert('Button clicked!');
});
document.getElementById('clickArea').addEventListener('click', function() {
this.style.backgroundColor = this.style.backgroundColor === 'lightblue' ? 'lightcoral' : 'lightblue';
});
// Form events
document.getElementById('myForm').addEventListener('submit', function(e) {
e.preventDefault(); // Prevent form submission
const input = document.getElementById('textInput');
alert('Form submitted with: ' + input.value);
});
// Input events
document.getElementById('textInput').addEventListener('input', function() {
console.log('Input value:', this.value);
});
// Keyboard events
document.getElementById('keyInput').addEventListener('keydown', function(e) {
console.log('Key pressed:', e.key);
});
// Mouse events
const mouseArea = document.getElementById('mouseArea');
mouseArea.addEventListener('mouseover', function() {
this.style.backgroundColor = 'yellow';
});
mouseArea.addEventListener('mouseout', function() {
this.style.backgroundColor = 'lightgreen';
});
mouseArea.addEventListener('mousemove', function(e) {
console.log('Mouse position:', e.clientX, e.clientY);
});
</script>
</body>
We will learn more about event handling in the Javascript section.
Form Validation with JavaScript
JavaScript can validate form data before submission to provide immediate feedback to users.
Client-side Validation
Client-side validation happens in the browser before the form is submitted to the server.
<body>
<form id="validationForm" novalidate>
<div>
<label for="email">Email:</label>
<input type="email" id="email" required>
<span id="emailError" style="color: red;"></span>
</div>
<div>
<label for="password">Password:</label>
<input type="password" id="password" required minlength="8">
<span id="passwordError" style="color: red;"></span>
</div>
<div>
<label for="confirmPassword">Confirm Password:</label>
<input type="password" id="confirmPassword" required>
<span id="confirmPasswordError" style="color: red;"></span>
</div>
<button type="submit">Submit</button>
</form>
<script>
const form = document.getElementById('validationForm');
const email = document.getElementById('email');
const password = document.getElementById('password');
const confirmPassword = document.getElementById('confirmPassword');
form.addEventListener('submit', function(e) {
e.preventDefault();
// Reset error messages
document.querySelectorAll('span[id$="Error"]').forEach(span => {
span.textContent = '';
});
let isValid = true;
// Validate email
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email.value)) {
document.getElementById('emailError').textContent = 'Please enter a valid email';
isValid = false;
}
// Validate password
if (password.value.length < 8) {
document.getElementById('passwordError').textContent = 'Password must be at least 8 characters';
isValid = false;
}
// Validate password confirmation
if (password.value !== confirmPassword.value) {
document.getElementById('confirmPasswordError').textContent = 'Passwords do not match';
isValid = false;
}
if (isValid) {
alert('Form submitted successfully!');
form.reset();
}
});
</script>
</body>
We will learn more about form validation in the Javascript section.