Now that you understand JavaScript basics, let's practice with hands-on exercises!
JavaScript & Interactivity Overview
JavaScript brings your web pages to life! In this section, you'll learn how to make your websites interactive and dynamic using JavaScript. From simple button clicks to complex form validation, JavaScript enables you to create engaging user experiences.
Learning Objectives
By the end of this part, you will be able to:
- Write and understand JavaScript code for web development
- Manipulate the DOM to change page content dynamically
- Handle user events like clicks, form submissions, and keyboard input
- Validate forms before submission
- Create interactive web elements that respond to user actions
JavaScript Basics for Web Development
What is JavaScript?
JavaScript is a programming language that enables interactive web pages. Unlike HTML (structure) and CSS (styling), JavaScript adds behavior and interactivity to your websites. It runs in the browser and can manipulate HTML elements, handle events, and create dynamic content.
Adding JavaScript to Your Page
JavaScript can be added to HTML documents in three ways, similar to CSS:
1. Inline JavaScript (In HTML attributes)
<button onclick="alert('Hello!')">Click Me</button>2. Internal JavaScript (In <script> tag)
<script>function greet() {
alert('Hello from JavaScript!');
}
</script>
3. External JavaScript (Recommended)
<script src="script.js"></script>// script.js file
function greet() {
alert('Hello from external file!');
}
Best Practices
- Use external JavaScript files: Better for organization and caching
- Place scripts before </body>: Ensures HTML loads first
- Use defer or async attributes: Control script loading behavior
- Keep JavaScript separate: Don't mix with HTML markup
Variables and Data Types
JavaScript uses variables to store data. Modern JavaScript uses let and const
for variable declarations:
Variables in JavaScript
// Using let (can be changed)let userName = 'John';
userName = 'Jane'; // OK
// Using const (cannot be changed)
const maxUsers = 100;
// maxUsers = 200; // Error!
// Data types
const text = 'Hello'; // String
const count = 42; // Number
const isActive = true; // Boolean
const user = null; // Null
Variables Demo
Functions
Functions are reusable blocks of code that perform specific tasks. They're essential for organizing your JavaScript code:
Function Declarations
// Function declarationfunction greetUser(name) {
return 'Hello, ' + name + '!';
}
// Arrow function (modern syntax)
const greetUser = (name) => {
return 'Hello, ' + name + '!';
};
// Calling the function
greetUser('Alice'); // Returns: "Hello, Alice!"
Functions Demo
Arrays and Objects
Arrays store lists of data, while objects store key-value pairs. Both are essential for web development:
Arrays and Objects
// Arrays - lists of itemsconst colors = ['red', 'green', 'blue'];
colors[0]; // 'red'
colors.push('yellow'); // Add item
// Objects - key-value pairs
const user = {
name: 'John',
email: 'john@example.com',
age: 30
};
user.name; // 'John'
user['email']; // 'john@example.com'
DOM Manipulation
What is the DOM?
The Document Object Model (DOM) is a representation of your HTML page that JavaScript can interact with. It's like a tree structure where each HTML element is a node that you can access, modify, add, or remove using JavaScript.
Selecting Elements
Before you can manipulate an element, you need to select it. JavaScript provides several methods to select elements:
Element Selection Methods
// Select by ID (returns single element)const header = document.getElementById('header');
// Select by class (returns array-like collection)
const cards = document.getElementsByClassName('card');
// Access individual elements using index
cards[0]; // First card (index 0)
cards[1]; // Second card (index 1)
cards[cards.length - 1]; // Last card
// Select by tag name
const paragraphs = document.getElementsByTagName('p');
paragraphs[0]; // First paragraph
// Modern query selectors (CSS selector syntax)
const firstCard = document.querySelector('.card'); // First match
const allCards = document.querySelectorAll('.card'); // All matches
// Access individual elements using index (like array)
allCards[0]; // First card (index 0)
allCards[1]; // Second card (index 1)
allCards[allCards.length - 1]; // Last card
// Loop through all elements
for (let i = 0; i < allCards.length; i++) {
allCards[i].style.color = 'blue'; // Change each card
}
// Or use forEach with querySelectorAll (NodeList supports forEach)
allCards.forEach((card, index) => {
card.style.backgroundColor = 'lightblue';
});
Selection Tips
- Use querySelector/querySelectorAll: Modern, flexible, and CSS-like syntax
- getElementById is fastest: Use when selecting by ID specifically
- Accessing collection elements: Use array-like indexing [0], [1], etc. to access individual elements
- Collection types: getElementsByClassName returns HTMLCollection, querySelectorAll returns NodeList (supports forEach)
- Loop through elements: Use for loops or forEach (with querySelectorAll) to modify all elements
- Check if element exists: Always verify element exists before using it
- Store selections in variables: Avoid repeated DOM queries
Changing Content
Once you've selected an element, you can change its content, styles, and attributes:
Modifying Elements
const element = document.querySelector('#myElement');// Change text content
element.textContent = 'New text';
element.innerHTML = '<strong>Bold text</strong>';
// Change styles
element.style.color = 'red';
element.style.backgroundColor = 'blue';
// Change attributes
element.setAttribute('class', 'new-class');
element.id = 'new-id';
Content Modification Demo
This text will change when you click the button.
Adding and Removing Elements
JavaScript allows you to dynamically add, remove, and move elements in the DOM:
Creating and Adding Elements
// Create new elementconst newDiv = document.createElement('div');
newDiv.textContent = 'New element';
newDiv.className = 'my-class';
// Append to existing element
const container = document.querySelector('#container');
container.appendChild(newDiv); // Add at the end
container.prepend(newDiv); // Add at the beginning
// Remove element
container.removeChild(newDiv);
// Or
newDiv.remove();
Add/Remove Elements Demo
Elements will appear here...
Event Handling
What are Events?
Events are actions that happen in the browser, such as clicks, form submissions, keyboard input, and page loads. JavaScript can listen for these events and respond with code.
Event Listeners
Event listeners "listen" for specific events and execute code when they occur. Modern JavaScript uses addEventListener for event handling:
Event Listener Syntax
// Select elementconst button = document.querySelector('#myButton');
// Add event listener
button.addEventListener('click', function() {
alert('Button clicked!');
});
// Using arrow function
button.addEventListener('click', () => {
console.log('Button clicked!');
});
Click Event Demo
Common Events
Here are the most commonly used events in web development:
Common Web Events
// Mouse eventselement.addEventListener('click', handler); // Click
element.addEventListener('dblclick', handler); // Double click
element.addEventListener('mouseover', handler); // Mouse over
element.addEventListener('mouseout', handler); // Mouse out
// Form events
form.addEventListener('submit', handler); // Form submit
input.addEventListener('change', handler); // Input change
input.addEventListener('focus', handler); // Input focus
input.addEventListener('blur', handler); // Input blur
// Keyboard events
input.addEventListener('keydown', handler); // Key pressed
input.addEventListener('keyup', handler); // Key released
Interactive Events Demo
Preventing Default Behavior
Some elements have default behaviors (like forms submitting, links navigating). You can prevent these default behaviors when needed:
Preventing Default Actions
// Prevent form submissionform.addEventListener('submit', function(e) {
e.preventDefault(); // Stop default form submit
// Your custom code here
});
// Prevent link navigation
link.addEventListener('click', function(e) {
e.preventDefault(); // Stop link navigation
// Your custom code here
});
Form Validation
Client-Side Validation
Form validation ensures users enter correct data before submitting. JavaScript can validate forms in real-time, providing immediate feedback to users.
Basic Validation
Here's how to validate form inputs with JavaScript:
Form Validation Example
form.addEventListener('submit', function(e) {e.preventDefault(); // Prevent default submission
const email = document.getElementById('email').value;
const password = document.getElementById('password').value;
// Validate email
if (email === '') {
alert('Email is required');
return false;
}
// Validate password length
if (password.length < 8) {
alert('Password must be at least 8 characters');
return false;
}
// If validation passes, submit form
form.submit();
});
Validation Demo
Real-Time Validation
You can validate forms as users type, providing immediate feedback:
Real-Time Validation
const emailInput = document.getElementById('email');const errorMessage = document.getElementById('email-error');
emailInput.addEventListener('input', function() {
const email = this.value;
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (email && !emailPattern.test(email)) {
errorMessage.textContent = 'Please enter a valid email';
this.style.borderColor = 'red';
} else {
errorMessage.textContent = '';
this.style.borderColor = 'green';
}
});