JavaScript Fundamentals

Add interactivity to your website with basic JavaScript.

Introduction to 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.

What You'll Need

  • Basic knowledge of HTML and CSS (see our First Web Page and CSS Basics guides)
  • A text editor (Notepad++, Visual Studio Code, or similar)
  • A modern web browser with Developer Tools (Chrome, Firefox, Edge, or Safari)

What Can JavaScript Do?

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

Adding JavaScript to Your Web Page

There are three ways to include JavaScript in your HTML document:

1. Internal JavaScript (Script Tag)

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>

2. External JavaScript File

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!');
}

Why External JavaScript is Better

Like external CSS, external JavaScript files offer several advantages:

  • Better organization of code
  • Reusability across multiple pages
  • Browser caching for faster page loads
  • Separation of concerns (HTML for content, JS for behavior)

3. Inline JavaScript

Add JavaScript directly to HTML elements using event attributes:

<button onclick="alert('Hello!')">Click Me</button>

Best Practice

Inline JavaScript should be used sparingly. For maintainable code, prefer external JavaScript files.

Script Placement

The placement of your <script> tag matters:

  • In the <head>: Scripts load before page content, which can delay rendering
  • At the end of <body>: Page content loads first, but scripts might not be available immediately

Modern Solution

Use the defer attribute to load scripts without blocking page rendering:

<head>
    <script src="script.js" defer></script>
</head>

JavaScript Syntax Fundamentals

Variables and Data Types

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:

  • String: Text values ("Hello" or 'Hello')
  • Number: Numeric values (42 or 3.14)
  • Boolean: true or false
  • Array: Collections of values ([1, 2, 3])
  • Object: Complex data with properties ({name: "John", age: 25})
  • Undefined: Variable declared but not assigned a value
  • Null: Intentional absence of value

Operators

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

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

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

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!");
});

DOM Manipulation

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.

Selecting Elements

// 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");

Changing HTML Content

// 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

Creating and Removing Elements

// 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();

Working with Classes

// 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");

Event Handling

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.

Common Events

  • click: When an element is clicked
  • mouseover / mouseout: When the mouse enters/leaves an element
  • keydown / keyup: When a keyboard key is pressed/released
  • submit: When a form is submitted
  • load: When the page finishes loading
  • resize: When the browser window is resized
  • scroll: When the user scrolls

Adding Event Listeners

// 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>

Event Object

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

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!");
    }
});

When to Use Event Delegation

Event delegation is useful when:

  • You have many similar elements that need the same event handler
  • You're dynamically adding elements to the page
  • You want to improve performance by reducing the number of event listeners

Practical JavaScript Examples

Example 1: Toggle Button

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";
    }
});

Example 2: Form Validation

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();
    }
});

Example 3: Image Slider

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();
});

Example 4: Tabbed Content

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");
    });
});

Debugging JavaScript

Using Console

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");

Browser Developer Tools

  1. Open Developer Tools:
    • Chrome/Edge: F12 or Right-click > Inspect
    • Firefox: F12 or Right-click > Inspect Element
    • Safari: Enable Developer Menu first, then Develop > Show Web Inspector
  2. Navigate to Console tab: View console output and run JavaScript
  3. Navigate to Sources/Debugger tab: Set breakpoints and debug code

Breakpoints and Debugger Statement

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;
}

Common JavaScript Errors

  • ReferenceError: Using a variable that doesn't exist
  • SyntaxError: Incorrectly written code (missing brackets, etc.)
  • TypeError: Using a value in an inappropriate way
  • Logic errors: Code works but doesn't do what you expect

JavaScript Best Practices

Code Organization

  • Use external JavaScript files
  • Organize your code into functions with specific purposes
  • Comment your code, especially complex sections
  • Use consistent indentation and formatting

Variable Naming

  • Use descriptive variable names (firstName instead of fn)
  • Use camelCase for variables and functions (myVariableName)
  • Use PascalCase for constructors and classes (MyClass)
  • Use UPPER_CASE for constants (MAX_SIZE)

Performance Tips

  • Minimize DOM manipulation
  • Use efficient selectors (getElementById is faster than querySelector)
  • Cache elements you use frequently
  • Be careful with loops on large data sets

Security Considerations

  • Never trust user input (always validate)
  • Be careful with innerHTML to avoid XSS attacks
  • Use textContent instead of innerHTML when displaying user input
  • Avoid using eval()

JavaScript Libraries and Frameworks

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

Learning Path

It's recommended to become comfortable with vanilla JavaScript before diving into frameworks. Understanding the fundamentals will make learning frameworks much easier.

Next Steps

Now that you understand JavaScript basics, here are some ways to continue learning:

  • Practice with small projects: Build a to-do list, calculator, or quiz app
  • Learn about AJAX and Fetch API: For retrieving data from servers
  • Explore modern JavaScript features: Arrow functions, template literals, destructuring
  • Study JSON (JavaScript Object Notation): For data interchange
  • Learn about local storage: For storing data in the browser
  • Explore JavaScript modules: For organizing larger codebases
  • Consider learning a framework: Once you're comfortable with vanilla JavaScript

JavaScript Resources

Free Learning Resources

Practice Websites

Tools

  • JSFiddle - Online code editor for testing JavaScript
  • CodePen - Social development environment for front-end code
  • ESLint - Linting utility for JavaScript

Need Help With JavaScript?

Contact us for personalized assistance with adding interactivity to your website.

Get in Touch
JavaScript Fundamentals | Syte.com

JavaScript Fundamentals

Add interactivity to your website with basic JavaScript.

Introduction to 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.

What You'll Need

  • Basic knowledge of HTML and CSS (see our First Web Page and CSS Basics guides)
  • A text editor (Notepad++, Visual Studio Code, or similar)
  • A modern web browser with Developer Tools (Chrome, Firefox, Edge, or Safari)

What Can JavaScript Do?

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

Adding JavaScript to Your Web Page

There are three ways to include JavaScript in your HTML document:

1. Internal JavaScript (Script Tag)

Add JavaScript directly in the HTML document using the <script> tag:

<!DOCTYPE html>
<html>
<head>
    &