Love at first Syte™
Add interactivity to your website with basic JavaScript.
JavaScript is a programming language that allows you to add dynamic behavior to your website. While HTML provides structure and CSS handles styling, JavaScript brings your site to life with interactive elements. With JavaScript, you can create slideshows, form validation, interactive maps, animations, and much more—all without requiring visitors to reload the page.
JavaScript enables a wide range of interactivity on websites:
| Feature | Example |
|---|---|
| DOM Manipulation | Change page content or styles without refreshing |
| Event Handling | Respond to user actions like clicking, scrolling, or typing |
| Form Validation | Check user input before form submission |
| Animations | Create smooth transitions and visual effects |
| API Integration | Fetch data from other websites or services |
| Interactive Components | Build sliders, tabs, accordions, and modals |
There are three ways to include JavaScript in your HTML document:
Add JavaScript directly in the HTML document using the <script> tag:
<!DOCTYPE html>
<html>
<head>
<title>My Web Page</title>
<script>
// JavaScript code goes here
function greet() {
alert('Hello, welcome to my website!');
}
</script>
</head>
<body>
<button onclick="greet()">Click Me</button>
</body>
</html>
Create a separate JavaScript file (with a .js extension) and link to it from your HTML:
<!-- In your HTML file -->
<!DOCTYPE html>
<html>
<head>
<title>My Web Page</title>
<script src="script.js"></script>
</head>
<body>
<button onclick="greet()">Click Me</button>
</body>
</html>
// In script.js file
function greet() {
alert('Hello, welcome to my website!');
}
Like external CSS, external JavaScript files offer several advantages:
Add JavaScript directly to HTML elements using event attributes:
<button onclick="alert('Hello!')">Click Me</button>
Inline JavaScript should be used sparingly. For maintainable code, prefer external JavaScript files.
The placement of your <script> tag matters:
Use the defer attribute to load scripts without blocking page rendering:
<head>
<script src="script.js" defer></script>
</head>
Variables store data values that can be used and changed throughout your code:
// Variable declaration with let (recommended for variables that change) let username = "John"; let age = 25; let isLoggedIn = true; // Variable declaration with const (for values that don't change) const PI = 3.14159; const MAX_USERS = 100; // Variable declaration with var (older method, less recommended) var counter = 0;
JavaScript has several data types:
"Hello" or 'Hello')42 or 3.14)true or false[1, 2, 3]){name: "John", age: 25})Operators perform operations on variables and values:
// Arithmetic operators let sum = 5 + 10; // Addition let difference = 10 - 5; // Subtraction let product = 5 * 10; // Multiplication let quotient = 10 / 5; // Division let remainder = 10 % 3; // Modulus (remainder) // Assignment operators let x = 10; // Assign value x += 5; // Same as: x = x + 5 x -= 3; // Same as: x = x - 3 x *= 2; // Same as: x = x * 2 x /= 4; // Same as: x = x / 4 // Comparison operators let isEqual = (5 == 5); // Equal to let isStrictEqual = (5 === "5"); // Strict equal to (value and type) let isNotEqual = (5 != 10); // Not equal to let isGreater = (10 > 5); // Greater than let isLess = (5 < 10); // Less than let isGreaterOrEqual = (10 >= 10); // Greater than or equal to let isLessOrEqual = (5 <= 5); // Less than or equal to // Logical operators let andResult = (true && false); // Logical AND let orResult = (true || false); // Logical OR let notResult = !true; // Logical NOT
Conditional statements perform different actions based on different conditions:
// if statement
let age = 18;
if (age >= 18) {
console.log("You are an adult");
}
// if-else statement
if (age >= 18) {
console.log("You are an adult");
} else {
console.log("You are a minor");
}
// if-else if-else statement
if (age < 13) {
console.log("Child");
} else if (age < 18) {
console.log("Teenager");
} else {
console.log("Adult");
}
// Switch statement
let day = 3;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
default:
console.log("Another day");
}
Loops execute a block of code multiple times:
// For loop
for (let i = 0; i < 5; i++) {
console.log("Iteration " + i);
}
// While loop
let count = 0;
while (count < 5) {
console.log("Count: " + count);
count++;
}
// Do-while loop (executes at least once)
let num = 0;
do {
console.log("Number: " + num);
num++;
} while (num < 5);
// For...of loop (for arrays)
const fruits = ["apple", "banana", "orange"];
for (const fruit of fruits) {
console.log(fruit);
}
// For...in loop (for objects)
const person = {name: "John", age: 30, job: "developer"};
for (const key in person) {
console.log(key + ": " + person[key]);
}
Functions are blocks of code designed to perform a particular task:
// Function declaration
function greet(name) {
return "Hello, " + name + "!";
}
// Function call
let message = greet("John");
console.log(message); // Output: Hello, John!
// Function with default parameter
function greetWithDefault(name = "Guest") {
return "Hello, " + name + "!";
}
console.log(greetWithDefault()); // Output: Hello, Guest!
// Arrow function (ES6+)
const multiply = (a, b) => a * b;
console.log(multiply(5, 3)); // Output: 15
// Function as an event handler
document.querySelector("button").addEventListener("click", function() {
alert("Button clicked!");
});
The Document Object Model (DOM) is a programming interface for web documents. JavaScript can change all the HTML elements and attributes in the page, as well as CSS styles.
// Select by ID
const element = document.getElementById("myId");
// Select by class name (returns a collection)
const elements = document.getElementsByClassName("myClass");
// Select by tag name (returns a collection)
const paragraphs = document.getElementsByTagName("p");
// Select using CSS selectors (returns first match)
const firstButton = document.querySelector(".btn");
// Select all matches using CSS selectors
const allButtons = document.querySelectorAll(".btn");
// Change text content
document.getElementById("demo").textContent = "New text content";
// Change HTML content
document.getElementById("demo").innerHTML = "<strong>New</strong> HTML content";
// Change attributes
document.getElementById("myImage").src = "newimage.jpg";
document.getElementById("myLink").href = "https://example.com";
// Change CSS styles
document.getElementById("demo").style.color = "blue";
document.getElementById("demo").style.fontSize = "20px";
document.getElementById("demo").style.display = "none"; // Hide element
// Create a new element
const newParagraph = document.createElement("p");
// Add text to the element
newParagraph.textContent = "This is a new paragraph.";
// Add the element to the document
document.body.appendChild(newParagraph);
// Add to a specific container
const container = document.getElementById("container");
container.appendChild(newParagraph);
// Remove an element
const elementToRemove = document.getElementById("oldElement");
elementToRemove.parentNode.removeChild(elementToRemove);
// Modern method to remove an element
elementToRemove.remove();
// Add a class
document.getElementById("myElement").classList.add("highlight");
// Remove a class
document.getElementById("myElement").classList.remove("old-class");
// Toggle a class (add if absent, remove if present)
document.getElementById("myElement").classList.toggle("active");
// Check if an element has a class
const hasClass = document.getElementById("myElement").classList.contains("active");
Events are actions that happen in the browser, like a button click or page load. JavaScript can "listen" for these events and execute code when they occur.
// Method 1: Using addEventListener (recommended)
document.getElementById("myButton").addEventListener("click", function() {
alert("Button was clicked!");
});
// Method 2: Using event properties
document.getElementById("myButton").onclick = function() {
alert("Button was clicked!");
};
// Method 3: Using HTML attribute (less recommended)
<button onclick="alert('Button was clicked!')">Click Me</button>
When an event is triggered, an event object is created with information about the event:
document.getElementById("myButton").addEventListener("click", function(event) {
// 'event' contains information about the event
console.log(event.type); // "click"
console.log(event.target); // The element that was clicked
console.log(event.clientX, event.clientY); // Mouse coordinates
// Prevent default behavior
event.preventDefault();
// Stop event propagation
event.stopPropagation();
});
Event delegation is a technique where you attach an event listener to a parent element and use the event object to identify which child element triggered the event:
// Instead of adding listeners to each button
document.getElementById("buttonContainer").addEventListener("click", function(event) {
// Check if the clicked element is a button
if (event.target.tagName === "BUTTON") {
alert("Button " + event.target.textContent + " was clicked!");
}
});
Event delegation is useful when:
A button that toggles an element's visibility:
<!-- HTML -->
<button id="toggleButton">Show/Hide Content</button>
<div id="content" style="display: none;">
This content can be toggled.
</div>
// JavaScript
document.getElementById("toggleButton").addEventListener("click", function() {
const content = document.getElementById("content");
if (content.style.display === "none") {
content.style.display = "block";
} else {
content.style.display = "none";
}
});
Basic form validation before submission:
<!-- HTML -->
<form id="myForm">
<input type="email" id="email" placeholder="Email">
<span id="emailError" class="error"></span>
<input type="password" id="password" placeholder="Password">
<span id="passwordError" class="error"></span>
<button type="submit">Submit</button>
</form>
// JavaScript
document.getElementById("myForm").addEventListener("submit", function(event) {
let isValid = true;
// Email validation
const email = document.getElementById("email").value;
if (!email.includes("@")) {
document.getElementById("emailError").textContent = "Please enter a valid email";
isValid = false;
} else {
document.getElementById("emailError").textContent = "";
}
// Password validation
const password = document.getElementById("password").value;
if (password.length < 6) {
document.getElementById("passwordError").textContent = "Password must be at least 6 characters";
isValid = false;
} else {
document.getElementById("passwordError").textContent = "";
}
// Prevent form submission if validation fails
if (!isValid) {
event.preventDefault();
}
});
A simple image slider:
<!-- HTML -->
<div class="slider">
<img id="sliderImage" src="image1.jpg" alt="Slider Image">
<div class="slider-controls">
<button id="prevBtn">Previous</button>
<button id="nextBtn">Next</button>
</div>
</div>
// JavaScript
const images = ["image1.jpg", "image2.jpg", "image3.jpg", "image4.jpg"];
let currentIndex = 0;
// Display the current image
function updateImage() {
document.getElementById("sliderImage").src = images[currentIndex];
}
// Previous button click
document.getElementById("prevBtn").addEventListener("click", function() {
currentIndex--;
if (currentIndex < 0) {
currentIndex = images.length - 1;
}
updateImage();
});
// Next button click
document.getElementById("nextBtn").addEventListener("click", function() {
currentIndex++;
if (currentIndex >= images.length) {
currentIndex = 0;
}
updateImage();
});
Create tabs to organize content:
<!-- HTML -->
<div class="tabs">
<div class="tab-buttons">
<button class="tab-button active" data-tab="tab1">Tab 1</button>
<button class="tab-button" data-tab="tab2">Tab 2</button>
<button class="tab-button" data-tab="tab3">Tab 3</button>
</div>
<div class="tab-content">
<div id="tab1" class="tab-panel active">Content for Tab 1</div>
<div id="tab2" class="tab-panel">Content for Tab 2</div>
<div id="tab3" class="tab-panel">Content for Tab 3</div>
</div>
</div>
// JavaScript
document.querySelectorAll(".tab-button").forEach(function(button) {
button.addEventListener("click", function() {
// Remove active class from all buttons and panels
document.querySelectorAll(".tab-button").forEach(function(btn) {
btn.classList.remove("active");
});
document.querySelectorAll(".tab-panel").forEach(function(panel) {
panel.classList.remove("active");
});
// Add active class to clicked button and corresponding panel
button.classList.add("active");
const tabId = button.getAttribute("data-tab");
document.getElementById(tabId).classList.add("active");
});
});
The console is a powerful tool for debugging JavaScript:
// Output simple message
console.log("This is a log message");
// Output warning
console.warn("This is a warning");
// Output error
console.error("This is an error");
// Output object details
const person = { name: "John", age: 30 };
console.log(person);
// Table format for arrays and objects
console.table(person);
// Time execution
console.time("Timer");
// ... code to time ...
console.timeEnd("Timer");
Breakpoints pause code execution so you can inspect variables:
function calculateTotal(price, quantity) {
// This line will pause execution when developer tools are open
debugger;
const subtotal = price * quantity;
const tax = subtotal * 0.08;
return subtotal + tax;
}
firstName instead of fn)myVariableName)MyClass)MAX_SIZE)getElementById is faster than querySelector)innerHTML to avoid XSS attackstextContent instead of innerHTML when displaying user inputeval()Once you're comfortable with vanilla JavaScript, you might want to explore libraries and frameworks that can save you time and effort:
| Library/Framework | Description | Best For |
|---|---|---|
| jQuery | Simplifies DOM manipulation and AJAX | Small to medium projects, beginners |
| React | Library for building user interfaces | Single-page applications, complex UIs |
| Vue.js | Progressive framework for UIs | Beginners to frameworks, versatile projects |
| Angular | Full-featured framework | Large enterprise applications |
| Bootstrap (JS component) | UI components with built-in JavaScript | Rapid prototyping, responsive design |
It's recommended to become comfortable with vanilla JavaScript before diving into frameworks. Understanding the fundamentals will make learning frameworks much easier.
Contact us for personalized assistance with adding interactivity to your website.
Get in Touch