HTML & JS Topic
HTML & JS Introduction
HTML Introduction
What is HTML?
HTML (HyperText Markup Language) is the standard markup language for creating web pages. It provides the structure of a webpage.
Basic HTML Document Structure
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My First Web Page</title>
</head>
<body>
<h1>Welcome to My Website</h1>
<p>This is a paragraph of text.</p>
</body>
</html>
HTML Elements and Tags
1. Basic Text Elements
html
<!-- Headings -->
<h1>Main Heading</h1>
<h2>Subheading</h2>
<h3>Smaller Heading</h3>
<!-- Paragraphs -->
<p>This is a paragraph. It can contain <strong>bold text</strong> and <em>italic text</em>.</p>
<!-- Lists -->
<ul>
<li>Unordered list item 1</li>
<li>Unordered list item 2</li>
</ul>
<ol>
<li>Ordered list item 1</li>
<li>Ordered list item 2</li>
</ol>
2. Links and Images
html
<!-- Links -->
<a href="https://www.example.com" target="_blank">Visit Example.com</a>
<a href="about.html">About Page</a>
<a href="#section1">Jump to Section 1</a>
<!-- Images -->
<img src="image.jpg" alt="Description of image" width="400" height="300">
<img src="https://picsum.photos/200/300" alt="Random image">
3. Forms and Inputs
html
<form action="/submit" method="POST">
<!-- Text Input -->
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<!-- Email Input -->
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<!-- Password -->
<label for="password">Password:</label>
<input type="password" id="password" name="password" minlength="8">
<!-- Dropdown -->
<label for="country">Country:</label>
<select id="country" name="country">
<option value="us">United States</option>
<option value="ca">Canada</option>
<option value="uk">United Kingdom</option>
</select>
<!-- Radio Buttons -->
<fieldset>
<legend>Gender:</legend>
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label>
</fieldset>
<!-- Checkboxes -->
<input type="checkbox" id="newsletter" name="newsletter" checked>
<label for="newsletter">Subscribe to newsletter</label>
<!-- Textarea -->
<label for="message">Message:</label>
<textarea id="message" name="message" rows="4" cols="50"></textarea>
<!-- Submit Button -->
<button type="submit">Submit Form</button>
</form>
4. Semantic HTML5 Elements
html
<header>
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/about">About</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
</nav>
</header>
<main>
<article>
<h1>Article Title</h1>
<p>Article content...</p>
</article>
<aside>
<h3>Related Links</h3>
<ul>
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
</ul>
</aside>
</main>
<section>
<h2>Features Section</h2>
<div class="features">
<div class="feature">
<h3>Feature 1</h3>
<p>Description</p>
</div>
</div>
</section>
<footer>
<p>© 2024 My Website. All rights reserved.</p>
</footer>
5. Tables
html
<table border="1">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>City</th>
</tr>
</thead>
<tbody>
<tr>
<td>John Doe</td>
<td>30</td>
<td>New York</td>
</tr>
<tr>
<td>Jane Smith</td>
<td>25</td>
<td>London</td>
</tr>
</tbody>
</table>
JavaScript Introduction
What is JavaScript?
JavaScript is a programming language that enables interactive web pages. It's:
-
Client-side - Runs in the browser
-
Dynamic - Can update content without page reload
-
Versatile - Used for frontend and backend (Node.js)
Including JavaScript in HTML
html
<!-- Internal JavaScript -->
<script>
console.log("Hello from internal JS!");
</script>
<!-- External JavaScript -->
<script src="script.js" defer></script>
<!-- Inline JavaScript (not recommended) -->
<button onclick="alert('Button clicked!')">Click me</button>
JavaScript Fundamentals
1. Variables and Data Types
javascript
// Variable declarations
var oldVariable = "I'm old school"; // Function-scoped
let modernVariable = "I'm modern"; // Block-scoped
const constantVariable = "I can't change"; // Constant
// Data Types
let string = "Hello World"; // String
let number = 42; // Number
let decimal = 3.14; // Number
let isTrue = true; // Boolean
let nothing = null; // Null
let notDefined = undefined; // Undefined
// Complex Types
let array = [1, 2, 3, "hello"]; // Array
let object = { // Object
name: "John",
age: 30,
isStudent: false
};
// Type checking
console.log(typeof string); // "string"
console.log(typeof number); // "number"
console.log(typeof isTrue); // "boolean"
console.log(typeof array); // "object"
console.log(Array.isArray(array)); // true
2. Operators
javascript
// Arithmetic Operators
let sum = 10 + 5; // 15
let difference = 10 - 5; // 5
let product = 10 * 5; // 50
let quotient = 10 / 5; // 2
let remainder = 10 % 3; // 1
// Comparison Operators
console.log(5 == "5"); // true (loose equality)
console.log(5 === "5"); // false (strict equality)
console.log(5 != "5"); // false
console.log(5 !== "5"); // true
console.log(10 > 5); // true
console.log(10 <= 10); // true
// Logical Operators
let and = true && false; // false
let or = true || false; // true
let not = !true; // false
// Ternary Operator
let age = 20;
let canVote = age >= 18 ? "Yes" : "No"; // "Yes"
3. Functions
javascript
// Function Declaration
function greet(name) {
return "Hello, " + name + "!";
}
// Function Expression
const multiply = function(a, b) {
return a * b;
};
// Arrow Function (ES6+)
const divide = (a, b) => a / b;
// Arrow function with multiple lines
const calculate = (a, b, operation) => {
if (operation === 'add') {
return a + b;
} else if (operation === 'multiply') {
return a * b;
}
return 0;
};
// Default parameters
function createUser(name, age = 18, isActive = true) {
return {
name: name,
age: age,
isActive: isActive
};
}
// Calling functions
console.log(greet("Alice")); // "Hello, Alice!"
console.log(multiply(5, 4)); // 20
console.log(divide(10, 2)); // 5
console.log(createUser("Bob")); // {name: "Bob", age: 18, isActive: true}
4. Control Structures
javascript
// If-Else Statements
let temperature = 25;
if (temperature > 30) {
console.log("It's hot outside!");
} else if (temperature > 20) {
console.log("It's warm outside!");
} else {
console.log("It's cool outside!");
}
// Switch Statement
let day = "Monday";
switch (day) {
case "Monday":
console.log("Start of the work week");
break;
case "Friday":
console.log("Weekend is coming!");
break;
default:
console.log("It's a regular day");
}
// Loops
// For loop
for (let i = 0; i < 5; i++) {
console.log("Iteration: " + i);
}
// While loop
let count = 0;
while (count < 3) {
console.log("Count: " + count);
count++;
}
// For...of loop (arrays)
const fruits = ["apple", "banana", "orange"];
for (const fruit of fruits) {
console.log(fruit);
}
// For...in loop (objects)
const person = { name: "John", age: 30 };
for (const key in person) {
console.log(key + ": " + person[key]);
}
5. Arrays
javascript
// Creating arrays
let numbers = [1, 2, 3, 4, 5];
let mixed = [1, "hello", true, null];
let empty = [];
// Array methods
numbers.push(6); // Add to end: [1,2,3,4,5,6]
numbers.pop(); // Remove from end: [1,2,3,4,5]
numbers.unshift(0); // Add to start: [0,1,2,3,4,5]
numbers.shift(); // Remove from start: [1,2,3,4,5]
// Common array operations
let doubled = numbers.map(num => num * 2); // [2,4,6,8,10]
let even = numbers.filter(num => num % 2 === 0); // [2,4]
let sum = numbers.reduce((acc, num) => acc + num, 0); // 15
// Finding elements
let found = numbers.find(num => num > 3); // 4
let exists = numbers.includes(3); // true
let index = numbers.indexOf(3); // 2
// Array destructuring
let [first, second, ...rest] = numbers; // first=1, second=2, rest=[3,4,5]
6. Objects
javascript
// Creating objects
let person = {
firstName: "John",
lastName: "Doe",
age: 30,
isEmployed: true,
// Method
getFullName: function() {
return this.firstName + " " + this.lastName;
},
// Shorthand method (ES6+)
greet() {
return "Hello, I'm " + this.getFullName();
}
};
// Accessing properties
console.log(person.firstName); // "John"
console.log(person["lastName"]); // "Doe"
console.log(person.getFullName()); // "John Doe"
// Adding/updating properties
person.email = "[email protected]";
person["phone"] = "123-456-7890";
// Object methods
let keys = Object.keys(person); // ["firstName", "lastName", ...]
let values = Object.values(person); // ["John", "Doe", ...]
let entries = Object.entries(person); // [["firstName", "John"], ...]
// Object destructuring
let { firstName, age, ...otherInfo } = person;
console.log(firstName); // "John"
console.log(age); // 30
// Spread operator
let personCopy = { ...person };
let updatedPerson = { ...person, age: 31 };
DOM Manipulation
1. Selecting Elements
javascript
// Different ways to select elements
let elementById = document.getElementById("myId");
let elementsByClass = document.getElementsByClassName("myClass");
let elementsByTag = document.getElementsByTagName("div");
// Modern selectors (CSS-like)
let element = document.querySelector("#myId .myClass");
let allElements = document.querySelectorAll(".myClass");
// Examples
let header = document.querySelector("header");
let buttons = document.querySelectorAll("button");
let firstParagraph = document.querySelector("p");
2. Modifying Elements
javascript
// Changing content
let heading = document.querySelector("h1");
heading.textContent = "New Title"; // Text only
heading.innerHTML = "New <em>Title</em>"; // HTML content
// Changing attributes
let image = document.querySelector("img");
image.src = "new-image.jpg";
image.alt = "New description";
// Changing styles
let div = document.querySelector("div");
div.style.color = "blue";
div.style.backgroundColor = "#f0f0f0";
div.style.fontSize = "20px";
// Adding/removing classes
div.classList.add("highlight");
div.classList.remove("old-class");
div.classList.toggle("active"); // Toggle on/off
// Creating new elements
let newParagraph = document.createElement("p");
newParagraph.textContent = "This is a new paragraph";
document.body.appendChild(newParagraph);
// Removing elements
let oldElement = document.querySelector("#old");
oldElement.remove();
3. Event Handling
javascript
// Inline events (HTML)
<button onclick="handleClick()">Click me</button>
// Traditional event listeners
let button = document.querySelector("button");
button.onclick = function() {
console.log("Button clicked!");
};
// Modern event listeners (recommended)
button.addEventListener("click", function(event) {
console.log("Button clicked!", event);
event.preventDefault(); // Prevent default behavior
});
// Common events
let input = document.querySelector("input");
input.addEventListener("input", function(e) {
console.log("Input changed:", e.target.value);
});
input.addEventListener("focus", function() {
console.log("Input focused");
});
input.addEventListener("blur", function() {
console.log("Input lost focus");
});
// Form submission
let form = document.querySelector("form");
form.addEventListener("submit", function(e) {
e.preventDefault(); // Prevent page reload
let formData = new FormData(form);
console.log("Form submitted:", Object.fromEntries(formData));
});
// Keyboard events
document.addEventListener("keydown", function(e) {
console.log("Key pressed:", e.key);
});
// Mouse events
let box = document.querySelector(".box");
box.addEventListener("mouseenter", function() {
this.style.backgroundColor = "yellow";
});
box.addEventListener("mouseleave", function() {
this.style.backgroundColor = "white";
});
Modern JavaScript Features (ES6+)
1. Template Literals
javascript
let name = "John";
let age = 30;
// Old way
let message = "Hello, " + name + ". You are " + age + " years old.";
// Template literals
let newMessage = `Hello, ${name}. You are ${age} years old.`;
// Multi-line strings
let multiLine = `
This is a
multi-line
string
`;
// Expressions
let calculation = `The result is: ${5 + 3 * 2}`; // "The result is: 11"
2. Destructuring
javascript
// Array destructuring
let numbers = [1, 2, 3, 4, 5];
let [first, second, third] = numbers; // first=1, second=2, third=3
let [a, b, ...rest] = numbers; // a=1, b=2, rest=[3,4,5]
// Object destructuring
let user = { name: "Alice", age: 25, email: "[email protected]" };
let { name, age } = user; // name="Alice", age=25
let { email: userEmail } = user; // userEmail="[email protected]"
// Function parameter destructuring
function printUser({ name, age }) {
console.log(`${name} is ${age} years old`);
}
printUser(user); // "Alice is 25 years old"
3. Spread and Rest Operators
javascript
// Spread operator (...)
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let combined = [...arr1, ...arr2]; // [1,2,3,4,5,6]
let obj1 = { a: 1, b: 2 };
let obj2 = { c: 3, d: 4 };
let merged = { ...obj1, ...obj2 }; // {a:1, b:2, c:3, d:4}
// Rest operator
function sum(...numbers) {
return numbers.reduce((acc, num) => acc + num, 0);
}
console.log(sum(1, 2, 3, 4)); // 10
4. Modules
javascript
// math.js (exporting)
export const PI = 3.14159;
export function add(a, b) {
return a + b;
}
export default function multiply(a, b) {
return a * b;
}
// app.js (importing)
import multiply, { PI, add } from './math.js';
console.log(PI); // 3.14159
console.log(add(2, 3)); // 5
console.log(multiply(2, 3)); // 6
Practical Examples
1. Interactive To-Do List
html
<!DOCTYPE html>
<html>
<head>
<title>Todo List</title>
<style>
.completed { text-decoration: line-through; color: gray; }
.todo-item { margin: 10px 0; padding: 10px; border: 1px solid #ddd; }
</style>
</head>
<body>
<h1>Todo List</h1>
<form id="todo-form">
<input type="text" id="todo-input" placeholder="Add a new todo" required>
<button type="submit">Add Todo</button>
</form>
<ul id="todo-list"></ul>
<script>
// DOM Elements
const form = document.getElementById('todo-form');
const input = document.getElementById('todo-input');
const todoList = document.getElementById('todo-list');
// Todo array
let todos = JSON.parse(localStorage.getItem('todos')) || [];
// Render todos
function renderTodos() {
todoList.innerHTML = '';
todos.forEach((todo, index) => {
const li = document.createElement('li');
li.className = `todo-item ${todo.completed ? 'completed' : ''}`;
li.innerHTML = `
<span>${todo.text}</span>
<button onclick="toggleTodo(${index})">
${todo.completed ? 'Undo' : 'Complete'}
</button>
<button onclick="deleteTodo(${index})">Delete</button>
`;
todoList.appendChild(li);
});
// Save to localStorage
localStorage.setItem('todos', JSON.stringify(todos));
}
// Add new todo
form.addEventListener('submit', function(e) {
e.preventDefault();
const text = input.value.trim();
if (text) {
todos.push({ text, completed: false });
input.value = '';
renderTodos();
}
});
// Toggle todo completion
window.toggleTodo = function(index) {
todos[index].completed = !todos[index].completed;
renderTodos();
};
// Delete todo
window.deleteTodo = function(index) {
todos.splice(index, 1);
renderTodos();
};
// Initial render
renderTodos();
</script>
</body>
</html>
2. Form Validation
javascript
function validateForm() {
const form = document.getElementById('signup-form');
const email = document.getElementById('email');
const password = document.getElementById('password');
const confirmPassword = document.getElementById('confirm-password');
let isValid = true;
// Clear previous errors
clearErrors();
// Email validation
if (!email.value.includes('@')) {
showError(email, 'Please enter a valid email address');
isValid = false;
}
// Password validation
if (password.value.length < 8) {
showError(password, 'Password must be at least 8 characters');
isValid = false;
}
// Confirm password
if (password.value !== confirmPassword.value) {
showError(confirmPassword, 'Passwords do not match');
isValid = false;
}
return isValid;
}
function showError(input, message) {
const errorDiv = document.createElement('div');
errorDiv.className = 'error-message';
errorDiv.style.color = 'red';
errorDiv.textContent = message;
input.parentNode.appendChild(errorDiv);
input.style.borderColor = 'red';
}
function clearErrors() {
const errors = document.querySelectorAll('.error-message');
errors.forEach(error => error.remove());
const inputs = document.querySelectorAll('input');
inputs.forEach(input => input.style.borderColor = '');
}
3. API Fetch Example
javascript
// Fetch data from API
async function fetchUsers() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
if (!response.ok) {
throw new Error('Network response was not ok');
}
const users = await response.json();
displayUsers(users);
} catch (error) {
console.error('Error fetching users:', error);
document.getElementById('user-list').innerHTML =
'<p>Error loading users. Please try again later.</p>';
}
}
function displayUsers(users) {
const userList = document.getElementById('user-list');
userList.innerHTML = '';
users.forEach(user => {
const userDiv = document.createElement('div');
userDiv.className = 'user-card';
userDiv.innerHTML = `
<h3>${user.name}</h3>
<p>Email: ${user.email}</p>
<p>Phone: ${user.phone}</p>
`;
userList.appendChild(userDiv);
});
}
// Post data to API
async function createUser(userData) {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(userData)
});
const newUser = await response.json();
console.log('User created:', newUser);
} catch (error) {
console.error('Error creating user:', error);
}
}
// Usage
fetchUsers();
Key Concepts Summary
HTML:
-
Structure web pages with semantic elements
-
Forms for user input
-
Accessibility with proper tags and attributes
-
SEO with meaningful structure
JavaScript:
-
Variables store data
-
Functions organize code
-
DOM Manipulation interacts with webpage
-
Events handle user interactions
-
Async/Await for API calls
-
ES6+ Features for modern development
Best Practices:
-
Use semantic HTML for better accessibility
-
Separate concerns - HTML for structure, CSS for style, JS for behavior
-
Use modern JavaScript features (ES6+)
-
Handle errors gracefully
-
Validate user input on both client and server side
-
Use meaningful variable names
-
Comment your code for clarity
This foundation in HTML and JavaScript will enable you to create interactive, dynamic web applications!
Comments (0)
No comments yet. Be the first to comment!