Advertisement

Learn JavaScript Basics: Add Interactivity to Websites

HTML and CSS make websites look good, but JavaScript makes them do things. Click buttons, show/hide content, validate forms, update pages without refreshing - that's JavaScript.

This course teaches you JavaScript basics. By the end, you'll be able to add interactivity to your websites. No prior programming experience needed - I'll explain everything.

What Is JavaScript?

JavaScript is a programming language that runs in web browsers. It lets you:

  • Respond to user actions (clicks, typing, etc.)
  • Change page content dynamically
  • Validate forms
  • Make websites interactive

It's different from Java (despite the name). JavaScript is specifically for web development.

Adding JavaScript to Your Page

You can add JavaScript in three ways:

1. Inline (in HTML):

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

2. In a <script> tag:

<script>
    alert('Hello, World!');
</script>

3. External file (recommended):

Create script.js:

alert('Hello, World!');

Link it in HTML (before closing </body>):

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

Use external files for real projects - it keeps code organized.

Variables

Variables store data. Think of them as labeled boxes:

let name = "John";
let age = 25;
let isStudent = true;

Types of data:

  • String: Text (in quotes) - "Hello"
  • Number: Numbers - 42
  • Boolean: True or false - true or false
  • Array: List of items - [1, 2, 3]
  • Object: Collection of properties - {name: "John", age: 25}

Declaring variables:

  • let - Can be changed
  • const - Cannot be changed (constant)
  • var - Old way (avoid if possible)

Functions

Functions are reusable blocks of code:

function greet(name) {
    return "Hello, " + name + "!";
}

let message = greet("John");
console.log(message); // "Hello, John!"

Arrow functions (modern way):

const greet = (name) => {
    return "Hello, " + name + "!";
}

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

Working with the DOM

The DOM (Document Object Model) is how JavaScript interacts with HTML. You can select elements and change them:

// Select element by ID
let heading = document.getElementById("myHeading");

// Select by class
let paragraphs = document.getElementsByClassName("myClass");

// Select by tag
let allDivs = document.getElementsByTagName("div");

// Modern way - select first matching element
let element = document.querySelector("#myId");

// Select all matching elements
let elements = document.querySelectorAll(".myClass");

Change content:

let heading = document.querySelector("h1");
heading.textContent = "New Heading";
heading.innerHTML = "New Heading";

Change styles:

let element = document.querySelector("#myDiv");
element.style.color = "red";
element.style.backgroundColor = "yellow";
Advertisement

Events

Events are user actions (clicks, typing, etc.). You can listen for them:

let button = document.querySelector("#myButton");

button.addEventListener("click", function() {
    alert("Button clicked!");
});

Common events:

  • click - Mouse click
  • mouseover - Mouse enters element
  • mouseout - Mouse leaves element
  • keydown - Key pressed
  • keyup - Key released
  • submit - Form submitted
  • change - Input value changed
  • load - Page loaded

Example - toggle visibility:

let button = document.querySelector("#toggleBtn");
let content = document.querySelector("#content");

button.addEventListener("click", function() {
    if (content.style.display === "none") {
        content.style.display = "block";
    } else {
        content.style.display = "none";
    }
});

Conditionals

Make decisions with if/else:

let age = 20;

if (age >= 18) {
    console.log("You're an adult");
} else {
    console.log("You're a minor");
}

Comparison operators:

  • == - Equal to (loose)
  • === - Equal to (strict - use this)
  • != - Not equal
  • !== - Not equal (strict)
  • > - Greater than
  • < - Less than
  • >= - Greater than or equal
  • <= - Less than or equal

Loops

Repeat code with loops:

For loop:

for (let i = 0; i < 5; i++) {
    console.log(i); // 0, 1, 2, 3, 4
}

For...of loop (arrays):

let fruits = ["apple", "banana", "orange"];

for (let fruit of fruits) {
    console.log(fruit);
}

While loop:

let i = 0;
while (i < 5) {
    console.log(i);
    i++;
}

Arrays

Arrays store lists of items:

let fruits = ["apple", "banana", "orange"];

// Access items (starts at 0)
console.log(fruits[0]); // "apple"

// Add item
fruits.push("grape");

// Remove last item
fruits.pop();

// Get length
console.log(fruits.length); // 3

Common array methods:

  • push() - Add to end
  • pop() - Remove from end
  • shift() - Remove from start
  • unshift() - Add to start
  • indexOf() - Find index of item
  • includes() - Check if item exists

Objects

Objects store related data:

let person = {
    name: "John",
    age: 25,
    city: "New York"
};

// Access properties
console.log(person.name); // "John"
console.log(person["age"]); // 25

// Change properties
person.age = 26;

// Add properties
person.email = "john@example.com";

Practical Example

Let's build a simple counter:

HTML:

<div id="counter">0</div>
<button id="increment">+</button>
<button id="decrement">-</button>

JavaScript:

let count = 0;
let counterDisplay = document.querySelector("#counter");
let incrementBtn = document.querySelector("#increment");
let decrementBtn = document.querySelector("#decrement");

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

incrementBtn.addEventListener("click", function() {
    count++;
    updateDisplay();
});

decrementBtn.addEventListener("click", function() {
    count--;
    updateDisplay();
});

This creates a working counter. Click buttons to increase or decrease the number.

Form Validation

Validate forms before submission:

let form = document.querySelector("#myForm");

form.addEventListener("submit", function(event) {
    event.preventDefault(); // Stop form submission
    
    let email = document.querySelector("#email").value;
    
    if (email === "") {
        alert("Email is required!");
        return;
    }
    
    if (!email.includes("@")) {
        alert("Invalid email!");
        return;
    }
    
    // If we get here, form is valid
    alert("Form submitted!");
    form.submit();
});

Common Mistakes

  • Forgetting quotes: Strings need quotes - "text" not text
  • Case sensitivity: JavaScript is case-sensitive - myVariable is different from MyVariable
  • Missing semicolons: Not required but good practice
  • Using == instead of ===: Use === for strict comparison
  • Not waiting for DOM: Put scripts at end of body or use DOMContentLoaded
  • Not checking console: Open browser console (F12) to see errors

Pro Tip: Always open the browser console (F12) when coding JavaScript. It shows errors and you can use console.log() to debug. Also, use console.log() liberally when learning - it helps you see what's happening. Don't be afraid to experiment and break things - that's how you learn.

Next Steps

Once you're comfortable with basics:

  • Learn about async/await and promises
  • Learn about JavaScript frameworks (React, Vue, etc.)
  • Practice by building interactive projects
  • Learn about APIs and fetching data
  • Study existing websites' JavaScript (view source)

Common Questions

Do I need to know HTML and CSS first?

Yes, definitely. JavaScript works with HTML and CSS. You need to understand the structure (HTML) and styling (CSS) before you can make things interactive with JavaScript.

How long does it take to learn JavaScript?

Basics take a week or two. Getting comfortable takes a few months. Mastery takes years. Start with basics, build projects, and keep learning. The key is practice.

Is JavaScript the same as Java?

No, completely different languages. JavaScript is for web development. Java is a general-purpose language. The names are similar but that's it.

Start Coding

Create an HTML file, add some JavaScript, and start experimenting. Build a button that changes text. Create a form validator. Make a simple game. The more you code, the better you'll get. JavaScript is powerful and fun once you get the hang of it.

Advertisement