JavaScript is a dynamic programming language that powers the interactive web. It's used for:
Web Development: Making websites interactive
Server Development: Building backend applications with Node.js
Mobile Apps: Creating cross-platform mobile applications
Desktop Apps: Building desktop applications
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:
End of <body>: Most common - HTML loads first
defer attribute: Script waits for HTML to finish
async attribute: Script loads in parallel
DOMContentLoaded: Wait for HTML to be ready
<!-- 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:
IDs for unique elements: #header, #main-btn
Classes for groups: .card, .button
Data attributes: data-value="123"
Form elements: input, select, textarea
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:
String: Text data ("Hello World")
Number: Numeric data (42, 3.14)
Boolean: True or false values
Array: List of values [1, 2, 3]
Object: Key-value pairs {key: "value"}
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:
Parameters: Input values (name, a, b)
Return: Output value from the function
Scope: Where variables can be accessed
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
// 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");
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';
}