1 / 15

JavaScript Fundamentals

Welcome to JavaScript! 🚀

JavaScript is a dynamic programming language that powers the interactive web. It's used for:

Let's start with a simple example:

Click the button above to see JavaScript in action!

Including JavaScript in HTML

Three Ways to Add JavaScript

1. Inline JavaScript (in HTML attributes):

<button onclick="alert('Hello World!')">Click Me</button> <p onmouseover="this.style.color='red'">Hover over me</p>

2. Internal JavaScript (in <script> tags):

<html> <head> <script> function greetUser() { alert("Welcome to our website!"); } </script> </head> <body> <button onclick="greetUser()">Greet</button> </body> </html>

3. External JavaScript (separate .js file):

<!-- In your HTML file --> <script src="script.js"></script> <!-- In script.js file --> function calculateSum(a, b) { return a + b; }

Try Different Methods:

Script Placement & Timing

Where and When to Load JavaScript

Script Placement Options:

<html> <head> <!-- Scripts in head load first --> <script src="early-script.js"></script> </head> <body> <h1>My Website</h1> <p>Content here...</p> <!-- Scripts at end of body load after HTML --> <script src="main-script.js"></script> </body> </html>

Best Practices:

<!-- Deferred loading --> <script src="script.js" defer></script> <!-- Async loading --> <script src="script.js" async></script> <!-- Wait for DOM to be ready --> <script> document.addEventListener('DOMContentLoaded', function() { // Your code here runs after HTML is loaded console.log('DOM is ready!'); }); </script>

Loading Demonstration:

Connecting JavaScript to HTML

Making HTML Elements Interactive

HTML Structure:

<!-- HTML with IDs and classes for JavaScript --> <div id="main-content"> <h2 class="title">Welcome!</h2> <button id="change-btn">Change Color</button> <p class="message">Click the button above</p> </div>

JavaScript Connection:

// Get elements by ID const button = document.getElementById('change-btn'); const message = document.querySelector('.message'); // Add event listener button.addEventListener('click', function() { message.style.color = 'blue'; message.textContent = 'Color changed!'; }); // Alternative: HTML onclick attribute // <button onclick="changeColor()">Click Me</button>

Common Patterns:

Live Connection Demo:

Interactive Title

Use the controls above to see JavaScript-HTML interaction!

Variables & Data Types

Storing and Working with Data

Variable Declaration:

let name = "Alice"; // String const age = 25; // Number var isStudent = true; // Boolean let hobbies = ["reading", "coding"]; // Array let person = { name: "Bob", age: 30 }; // Object

Data Types:

Try it yourself:

Functions

Reusable Blocks of Code

Function Declaration:

// Function declaration function greet(name) { return "Hello, " + name + "!"; } // Function expression const add = function(a, b) { return a + b; }; // Arrow function (ES6) const multiply = (a, b) => a * b;

Key Concepts:

Interactive Functions:

Control Structures

Making Decisions and Loops

Conditional Statements:

let score = 85; if (score >= 90) { console.log("Grade A"); } else if (score >= 80) { console.log("Grade B"); } else { console.log("Grade C"); }

Loops:

// For loop for (let i = 0; i < 5; i++) { console.log("Count: " + i); } // While loop let count = 0; while (count < 3) { console.log("While: " + count); count++; }

See Control Structures in Action:

Arrays

Working with Lists of Data

Creating and Manipulating Arrays:

let fruits = ["apple", "banana", "orange"]; // Adding elements fruits.push("grape"); // Add to end fruits.unshift("mango"); // Add to beginning // Removing elements fruits.pop(); // Remove from end fruits.shift(); // Remove from beginning // Accessing elements console.log(fruits[0]); // First element console.log(fruits.length); // Array length

Array Methods:

Array Operations:

Objects

Structured Data with Properties

Creating and Using Objects:

let student = { name: "Sarah", age: 20, courses: ["Math", "Physics"], isEnrolled: true, // Method (function inside object) introduce: function() { return "Hi, I'm " + this.name; } }; // Accessing properties console.log(student.name); // Dot notation console.log(student["age"]); // Bracket notation console.log(student.introduce()); // Calling method

Object Features:

Object Manipulation:

DOM Manipulation

Interacting with Web Pages

Selecting Elements:

// Select by ID let element = document.getElementById("myId"); // Select by class let elements = document.getElementsByClassName("myClass"); // Select by CSS selector let element = document.querySelector(".myClass"); let elements = document.querySelectorAll("p");

Modifying Elements:

// Change content element.textContent = "New text"; element.innerHTML = "<strong>Bold text</strong>"; // Change style element.style.color = "red"; element.style.fontSize = "20px"; // Add/remove classes element.classList.add("active"); element.classList.remove("inactive");

Live DOM Demo:

This text will change!

Events

Responding to User Interactions

Adding Event Listeners:

// Method 1: addEventListener button.addEventListener("click", function() { console.log("Button clicked!"); }); // Method 2: Arrow function button.addEventListener("click", () => { console.log("Button clicked!"); }); // Method 3: HTML attribute // <button onclick="handleClick()">Click me</button>

Common Events:

Event Examples:

Interact with the elements above!

Working with Forms

Collecting and Validating User Input

HTML Form Elements:

<form id="userForm"> <input type="text" id="userName" placeholder="Enter your name"> <input type="email" id="userEmail" placeholder="Enter your email"> <input type="number" id="userAge" placeholder="Enter your age"> <select id="userCountry"> <option value="usa">USA</option> <option value="canada">Canada</option> <option value="uk">UK</option> </select> <button type="button" onclick="processForm()">Submit</button> </form>

JavaScript Form Handling:

function processForm() { // Get form values let name = document.getElementById('userName').value; let email = document.getElementById('userEmail').value; let age = document.getElementById('userAge').value; // Validate input if (name === '' || email === '' || age === '') { alert('Please fill in all fields!'); return; } // Process the data console.log('User data:', {name, email, age}); }

Live Form Demo:

Fill out the form above and click Submit!

Advanced Button Interactions

Creating Dynamic and Interactive Buttons

Button States and Behavior:

// Change button text and behavior function toggleButton() { let btn = document.getElementById('toggleBtn'); if (btn.textContent === 'Click Me') { btn.textContent = 'Clicked!'; btn.style.backgroundColor = 'green'; } else { btn.textContent = 'Click Me'; btn.style.backgroundColor = 'blue'; } } // Disable/Enable buttons function disableButton() { document.getElementById('myBtn').disabled = true; document.getElementById('myBtn').textContent = 'Disabled'; }

Button Event Patterns:

// Multiple event types on same button let button = document.getElementById('multiBtn'); button.addEventListener('click', function() { console.log('Button clicked!'); }); button.addEventListener('mouseenter', function() { this.style.transform = 'scale(1.1)'; }); button.addEventListener('mouseleave', function() { this.style.transform = 'scale(1)'; });

Dynamic Button Creation:

function createButton(text, color) { let newButton = document.createElement('button'); newButton.textContent = text; newButton.style.backgroundColor = color; newButton.onclick = function() { alert('You clicked: ' + text); }; document.body.appendChild(newButton); }

Interactive Button Examples:

Toggle Button:

Counter Button:

Color Changer Buttons:

Dynamic Button Creator:

Dynamic buttons will appear here...

Try the interactive buttons above!

Best Practices

Writing Clean, Maintainable Code

Code Style:

Good vs Bad Examples:

// ❌ Bad var x = document.getElementById("n"); x.innerHTML = "Hello"; // ✅ Good const nameElement = document.getElementById("userName"); nameElement.textContent = "Hello, User!";

Debugging Tips: