JavaScript Basics:
JavaScript is a versatile programming language primarily used to create dynamic, interactive, and engaging web applications. It enhances the user experience by enabling features such as form validation, animations, interactive maps, and real-time updates without requiring a page reload. JavaScript can manipulate HTML and CSS to dynamically update content, style, and structure on a webpage. It’s widely used for front-end development alongside frameworks like React, Angular, and Vue.js. Additionally, with the advent of Node.js, JavaScript is also used for back-end development, enabling full-stack web development. Its ability to integrate with APIs and other technologies makes it essential for modern web development.
Variables in JavaScript
Variables in JavaScript are used to store data values. They can be declared using var, let, or const.
- var: Used in older versions; function-scoped and can be reassigned.
- let: Block-scoped; allows reassignment.
- const: Block-scoped; cannot be reassigned after initialization.
Example:
let age = 25; const name = "John";
Data Types in JavaScript
JavaScript supports two main categories:
a. Primitive Data Types:
- String: Text values (“Hello”, ‘World’).
- Number: Numeric values (42, 3.14).
- Boolean: Logical values (true, false).
- Null: Represents intentional absence of value (null).
- Undefined: Variable declared but not assigned a value.
- Symbol: Unique and immutable values (introduced in ES6).
- BigInt: For very large numbers beyond the safe integer limit.
b. Non-Primitive Data Types:
- Object: Complex structures (e.g., arrays, functions, and objects).
Example:
let car = { brand: "Toyota", model: "Corolla" }; let numbers = [1, 2, 3];
Operators in JavaScript
a. Arithmetic Operators: Perform mathematical calculations:
+, -, *, /, %, ++, –.
Example:
let sum = 5 + 3; // 8
b. Assignment Operators: Assign values:
=, +=, -=, *=, /=, %=.
Example:
let x = 10; x += 5; // 15
c. Comparison Operators: Compare values:
==, ===, !=, !==, <, >, <=, >=.
Example:
5 === '5'; // false (strict comparison)
d. Logical Operators: Combine or invert conditions:
&& (AND), || (OR), ! (NOT).
Example:
let a = true, b = false; console.log(a && b); // false
Other Operators:
- Ternary Operator: condition ? value1 : value2
- Typeof Operator: Determines data type: typeof.
Example:
let dataType = typeof 42; // "number"
Functions and Events
Types of Functions:
Functions in JavaScript are blocks of reusable code that perform a specific task. They can be predefined (built-in) or user-defined.
Function Declaration:
Defined using the function keyword and can be called before or after their declaration (hoisting applies).
function greet(name) { return `Hello, ${name}!`; } console.log(greet("John")); // Output: Hello, John!
Function Expression:
Assigned to a variable and cannot be called before their definition.
const greet = function(name) { return `Hi, ${name}!`; }; console.log(greet("Alice")); // Output: Hi, Alice!
Arrow Functions:
Introduced in ES6, they are concise and do not bind their own this.
const greet = (name) => `Welcome, ${name}!`; console.log(greet("Emma")); // Output: Welcome, Emma!
Anonymous Functions:
Functions without a name, often used as arguments in methods.
setTimeout(function() { console.log("Anonymous Function Executed!"); }, 1000);
Parameters and Arguments:
Functions can accept inputs (parameters) and return outputs.
function add(a, b) { return a + b; } console.log(add(3, 5)); // Output: 8
JavaScript Events:
Events are actions or occurrences (e.g., clicks, keypresses) that happen in the browser, which JavaScript can respond to using event listeners.
Common Events:
- onclick: Triggered when an element is clicked.
- onmouseover: Triggered when the mouse hovers over an element.
- onkeydown: Triggered when a key is pressed.
- onload: Triggered when the webpage finishes loading.
Event Handling Methods:
Inline Event Handler:
Defined directly in HTML attributes.
<button onclick="alert('Button clicked!')">Click Me</button>
Traditional DOM Event Handler:
Uses the on property of an element.
const btn = document.getElementById("myButton"); btn.onclick = function() { alert("Button clicked!"); };
Event Listener:
Preferred way to handle events as it allows multiple listeners for the same event.
const btn = document.getElementById("myButton"); btn.addEventListener("click", () => { alert("Button clicked using Event Listener!"); });
Event Example:
<!DOCTYPE html> <html> <head> <title>Event Example</title> </head> <body> <button id="myButton">Click Me</button> <script> const button = document.getElementById("myButton"); button.addEventListener("click", () => { alert("You clicked the button!"); }); </script> </body> </html>
Both functions and events are essential in JavaScript to build interactive and dynamic web applications.
c. DOM Manipulation
The “Document Object Model (DOM)” is a programming interface for HTML and XML documents. It represents the structure of a webpage as a tree, where elements are nodes. JavaScript can be used to interact with and manipulate the DOM to change the content, structure, and style of a webpage dynamically.
Common DOM Manipulation Methods:
1. Selecting Elements
JavaScript provides methods to select elements in the DOM:
- getElementById(): Selects an element by its `id`.
- getElementsByClassName(): Selects elements by their class name.
- getElementsByTagName(): Selects elements by their tag name.
- querySelector(): Selects the first element that matches a CSS selector.
- querySelectorAll(): Selects all elements that match a CSS selector.
Example:
const heading = document.getElementById("main-heading"); const items = document.querySelectorAll(".list-item");
2. Manipulating Content
- textContent: Sets or gets the text inside an element.
- innerHTML: Sets or gets the HTML inside an element.
- outerHTML: Gets or replaces the element, including its tags.
Example:
const heading = document.getElementById("main-heading"); heading.textContent = "Welcome to JavaScript!";
3. Manipulating Attributes
setAttribute: Adds or changes an attribute.
getAttribute: Gets the value of an attribute.
removeAttribute: Removes an attribute.
Example:
const link = document.querySelector("a"); link.setAttribute("href", "https://example.com"); link.setAttribute("target", "_blank");
4. Adding/Removing Classes
The ‘classList’ property allows manipulation of element classes:
- add(): Adds a class.
- remove(): Removes a class.
- toggle(): Toggles a class.
- contains(): Checks if a class exists.
Example:
const box = document.querySelector(".box"); box.classList.add("active"); box.classList.toggle("hidden");
5. Adding and Removing Elements
- createElement: Creates a new element.
- appendChild: Appends a child element.
- removeChild: Removes a child element.
Example:
const ul = document.querySelector("ul"); const newLi = document.createElement("li"); newLi.textContent = "New List Item"; ul.appendChild(newLi); // Removing an element const firstLi = ul.querySelector("li"); ul.removeChild(firstLi);
6. Styling Elements
Use the **`style`** property to apply inline CSS styles.
Example:
const box = document.querySelector(".box"); box.style.backgroundColor = "blue"; box.style.color = "white"; box.style.padding = "20px";
Example: DOM Manipulation
<!DOCTYPE html> <html> <head> <title>DOM Manipulation Example</title> </head> <body> <h1 id="main-heading">Hello, World!</h1> <ul> <li class="list-item">Item 1</li> <li class="list-item">Item 2</li> <li class="list-item">Item 3</li> </ul> <button id="change-btn">Change Heading</button> <script> // Select elements const heading = document.getElementById("main-heading"); const button = document.getElementById("change-btn"); const items = document.querySelectorAll(".list-item"); // Change text content button.addEventListener("click", () => { heading.textContent = "DOM Manipulation in Action!"; heading.style.color = "green"; // Add a new list item const ul = document.querySelector("ul"); const newLi = document.createElement("li"); newLi.textContent = "New Item Added!"; ul.appendChild(newLi); }); </script> </body> </html>
Bootstrap Framework
a. Grid System and Layout Design
- Importance of responsive design.
- Grid system: Rows and columns.
- Common classes: .container, .row, .col-md-4, .col-sm-6.
Example:
<div class="container"> <div class="row"> <div class="col-md-6">Column 1</div> <div class="col-md-6">Column 2</div> </div> </div>
b. Responsive Utilities
Hiding/showing elements on different screen sizes using classes like .d-none, .d-md-block.
Example:
<div class="d-none d-md-block">Visible only on medium screens and larger</div>
c. Common Bootstrap Components
Examples:
Navbar:
<nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#">Brand</a> </nav>
Buttons:
<button class="btn btn-primary">Primary Button</button>
Cards:
<div class="card" style="width: 18rem;"> <div class="card-body"> <h5 class="card-title">Card Title</h5> <p class="card-text">Some text here.</p> </div> </div>
Modals:
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal"></button>
Launch Modal
<div class="modal fade" id="exampleModal"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-body">Modal Content</div> </div> </div> </div>
Lab Exercise:
Build a responsive portfolio or product showcase page with Bootstrap and JavaScript.
Specifications:
- Layout:
- Use Bootstrap’s grid system for a responsive layout.
- Include a navbar, a hero section, and a card grid.
- Interactivity:
- Add a button that toggles the visibility of a description section using JavaScript.
- Add a modal that displays when a product or portfolio item is clicked.