Learn Javascript for Web Development Jump to this section

What is JavaScript? Jump to this section

Learn all of the JavaScript basics that you need to know to make your first website. This section will focus on how to use JavaScript to interact with webpages, without covering too much of the syntax or programming details.

JavaScript (not to be confused with Java) is a programming language that:

  • Runs in your web browser
  • Makes web pages interactive
  • Can update content dynamically
  • Responds to user actions
  • Can communicate with servers

How JavaScript Works with HTML/CSS Jump to this section

JavaScript can:

  • Change HTML content
  • Change CSS styles
  • Respond to user events (clicks, typing, etc.)
  • Calculate and manipulate data
  • Communicate with web servers

Adding JavaScript to Your Page Jump to this section

1. Inline JavaScript Jump to this section

Add JavaScript directly in HTML elements using event attributes.

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

2. Internal JavaScript Jump to this section

Add JavaScript between <script> tags, typically at the end of the <body> section.

Click the button to see JavaScript in action!
<button id="myButton">Click Me</button>

<script> let button = document.getElementById('myButton'); button.addEventListener('click', function() { alert('Hello from JavaScript!'); }); </script>

3. External JavaScript (Recommended) Jump to this section

Create a separate JavaScript file and link to it from your HTML. Best for larger projects and organization.

// script.js
console.log('Script loaded!');
<head>
    <script src="script.js" defer></script>
</head>

Note: defer makes the script run after the HTML loads. This helps the page load faster.

Pop-ups & Console Jump to this section

Alert Boxes Jump to this section

Display a simple message to the user.

alert("Welcome to my website!");

Confirm Boxes Jump to this section

Ask the user a yes/no question.

Click the button to see a confirmation dialog
let result = confirm("Are you sure you want to delete this?");

if (result) { alert("Deleted!"); } else { alert("Cancelled!"); }

Prompt Boxes Jump to this section

Get text input from the user.

Click the button to enter your name
let name = prompt("What's your name?");
alert("Hello, " + name);

console.log() Jump to this section

Use console.log() to output messages in the Browser Dev Tools console. This is essential for debugging.

Check your browser console (F12 → Console tab)
// Debug messages (only visible in dev tools)
console.log("Button was clicked!");
console.log("User data:", {name: "Alice", age: 25});
console.warn("This is a warning");
console.error("Something went wrong");

// Check values while coding let x = 5; console.log("x =", x);

Accessing Browser Dev Tools Jump to this section

To access the console:

  • Press F12 or Right-click → Inspect
  • Go to "Console" tab to see console.log() output
  • Go to "Elements" tab to see your HTML layout
  • Use "Sources" tab to debug step-by-step

Tip: Don't be afraid to use console.log() anywhere you want while learning. It won't affect what users see, but helps you understand what's happening.

Selecting HTML Elements Jump to this section

The DOM (Document Object Model) is how JavaScript interacts with HTML. You must first select elements before you can manipulate them.

Example HTML Structure Jump to this section

Card Title

Some description text

<div class="card">
    <h2 id="title">Card Title</h2>
    <p class="description">Some description text</p>
</div>

By ID (Fastest, Most Specific) Jump to this section

Select a single element by its unique id attribute.

Element with ID
let header = document.getElementById('main-header');

// Now you can use 'header' to modify that element header.textContent = "New Title";

By CSS Selector (Most Flexible) Jump to this section

Select elements using CSS selector syntax. Use querySelector() for the first match or querySelectorAll() for all matches.

Button 1
Button 2
Button 3
// Select first match
let firstButton = document.querySelector('.btn');

// Select all matches let allButtons = document.querySelectorAll('.btn');

// Loop through all matches allButtons.forEach(function(button) { console.log(button); });

By Tag or Class Name Jump to this section

Select elements by their HTML tag name or class name.

Click a button to see how many elements are selected
// By tag name
let paragraphs = document.getElementsByTagName('p');

// By class name let cards = document.getElementsByClassName('card');

// These return collections, not single elements console.log("Found " + paragraphs.length + " paragraphs");

Manipulating Elements Jump to this section

Once you've selected an element, you can modify its content, styles, and attributes.

Changing Content Jump to this section

textContent (Plain Text Only) Jump to this section

Original text
let element = document.getElementById('my-element');
element.textContent = "New text";

innerHTML (HTML Content) Jump to this section

Plain text
let element = document.getElementById('my-element');
element.innerHTML = "<strong>Bold text</strong>";

Changing Styles Jump to this section

Modify CSS properties directly using JavaScript.

Style this text
let element = document.getElementById('my-element');

// Change color element.style.color = "red";

// Change font size element.style.fontSize = "20px";

// Hide element element.style.display = "none";

// Show element again element.style.display = "block";

Working with CSS Classes Jump to this section

Instead of changing individual styles, toggle CSS classes for cleaner code.

Target element
let element = document.getElementById('myElement');

// Add a class element.classList.add('highlight');

// Remove a class element.classList.remove('highlight');

// Toggle class (add if missing, remove if present) element.classList.toggle('highlight');

// Check if class exists if (element.classList.contains('highlight')) { console.log("It's highlighted!"); }

Getting Information from Elements Jump to this section

Type in the input and click the button
let input = document.getElementById('myInput');

// Get form input value let value = input.value;

// Get image source let image = document.getElementById('myImage'); let src = image.src;

// Get link destination let link = document.getElementById('myLink'); let href = link.href;

Events Jump to this section

Events let you respond to what users do on your webpage.

Click Events Jump to this section

The most common event - triggered when an element is clicked.

Not clicked yet
let button = document.getElementById('myButton');
let message = document.getElementById('message');

button.addEventListener('click', function() { message.textContent = "Button was clicked!"; message.style.color = "green"; });

Mouse Events Jump to this section

Respond to mouse movements and interactions.

Hover over me!
let element = document.getElementById('myElement');

// Mouse enters element element.addEventListener('mouseover', function() { element.style.backgroundColor = "yellow"; });

// Mouse leaves element element.addEventListener('mouseout', function() { element.style.backgroundColor = ""; });

Image Toggle Example Jump to this section

Click to toggle between two states.

OFF
let image = document.getElementById('myImage');

image.addEventListener('click', function() { if (image.src.includes('off.jpg')) { image.src = 'on.jpg'; } else { image.src = 'off.jpg'; } });

Form Events Jump to this section

Respond to input changes and form interactions.

Start typing to see changes...
let input = document.getElementById('nameInput');

// Fires on every keystroke input.addEventListener('input', function() { console.log("Current value:", input.value); });

// When input gains focus input.addEventListener('focus', function() { input.style.border = "2px solid blue"; });

// When input loses focus input.addEventListener('blur', function() { input.style.border = ""; });

Keyboard Events Jump to this section

Respond to keyboard input.

Press Enter in the input field
document.addEventListener('keydown', function(event) {
    if (event.key === 'Enter') {
        alert("You pressed Enter!");
    }

// Other useful keys: // event.key === 'Escape' // event.key === ' ' (spacebar) // event.key === 'ArrowUp' });

Page Events Jump to this section

Respond to page loading and scrolling.

Load Event: Fires when page is fully loaded

Scroll Event: Fires when user scrolls

// When page fully loads
window.addEventListener('load', function() {
    console.log("Page fully loaded");
});

// When user scrolls window.addEventListener('scroll', function() { console.log("Scrolled to:", window.scrollY); });

Basic Syntax Jump to this section

You don't need to be a JavaScript expert to add interactivity. Here are the essentials:

Variables (Storing Data) Jump to this section

Variables store information that you can use and update later.

Click count: 0
let clickCount = 0;        // Numbers
let userName = "Alice";    // Text (strings)
let isActive = true;       // True/false (booleans)

// Use them to track state button.addEventListener('click', function() { clickCount++; console.log("Clicked " + clickCount + " times"); });

If Statements (Making Decisions) Jump to this section

Execute code conditionally based on whether something is true or false.

Enter an age and click the button
let age = document.getElementById('age').value;

if (age >= 18) { alert("You can vote!"); } else { alert("Too young to vote"); }

// Check if element exists let element = document.getElementById('maybe-exists'); if (element) { element.style.color = "red"; }

Functions (Reusable Actions) Jump to this section

Functions let you write code once and use it multiple times.

Click either button
// Define a function
function updateColor() {
    document.body.style.backgroundColor = "lightblue";
}

// Use it multiple times button1.addEventListener('click', updateColor); button2.addEventListener('click', updateColor);

Functions with Parameters Jump to this section

Functions can accept inputs (parameters) to make them more flexible.

Title
Subtitle
// Function with parameters
function changeText(elementId, newText) {
    document.getElementById(elementId).textContent = newText;
}

// Use with different inputs changeText('title', 'New Title'); changeText('subtitle', 'New Subtitle');

Practical Examples Jump to this section

Show/Hide Content Jump to this section

Toggle content visibility with a button click.

<div id="secretContent" style="display: none;">
    Hidden message here!
</div>
<button onclick="toggleSecret()">Toggle Secret</button>
function toggleSecret() {
    let content = document.getElementById('secretContent');

if (content.style.display === 'none') { content.style.display = 'block'; } else { content.style.display = 'none'; } }

Simple Form Validation Jump to this section

Validate user input before submission.

Enter a username and submit
<input type="text" id="username">
<button onclick="validateForm()">Submit</button>
<p id="error"></p>
function validateForm() {
    let username = document.getElementById('username').value;
    let error = document.getElementById('error');

if (username.length < 3) { error.textContent = "Username too short!"; error.style.color = "red"; } else { error.textContent = "Valid!"; error.style.color = "green"; } }

Dark Mode Toggle Jump to this section

Switch between light and dark themes.

This content changes with dark mode

<button onclick="toggleDarkMode()">
    Dark Mode Toggle
</button>
function toggleDarkMode() {
    document.body.classList.toggle('dark-mode');
}
/* CSS */
.dark-mode {
    background-color: black;
    color: white;
}

Counter Application Jump to this section

Track and display a count with increment/decrement buttons.

0
let count = 0;
let display = document.getElementById('counter');

function updateDisplay() { display.textContent = count; }

document.getElementById('increment').addEventListener('click', function() { count++; updateDisplay(); });

document.getElementById('decrement').addEventListener('click', function() { count--; updateDisplay(); });

document.getElementById('reset').addEventListener('click', function() { count = 0; updateDisplay(); });

Color Changer Jump to this section

Change background color with button clicks.

Click buttons to change color
let box = document.getElementById('colorBox');

document.getElementById('blueBtn').addEventListener('click', function() { box.style.backgroundColor = '#87b7d9'; });

document.getElementById('greenBtn').addEventListener('click', function() { box.style.backgroundColor = '#7ecd84'; });

document.getElementById('redBtn').addEventListener('click', function() { box.style.backgroundColor = '#d78b96'; });