Module-3
JAVASCRIPT AND HTML DOCUMENTS: The JavaScript execution
environment; The Document Object Model; Element access in JavaScript;
Events and event handling; Handling events from the Body elements,
Button elements, Text box and Password elements DYNAMIC
DOCUMENTS WITH JAVASCRIPT: Introduction to dynamic
documents; Positioning elements; Moving elements; Element visibility;
Changing colors and fonts; Dynamic content; Stacking elements; Locating
the mouse cursor; Reacting to a mouse click; Slow movement of
elements; Dragging and dropping elements.
The JavaScript Execution Environment
The JavaScript execution environment refers to the context where
JavaScript code is run. It defines the resources and APIs available to the
code.
Components of the Execution Environment
• Global Object:
• In the browser, the global object is window.
• In Node.js, it's global.
• The global object provides global variables and functions
(e.g., console, setTimeout, document).
Example:
• console.log(window.alert === alert); // true
1.JavaScript Engine:
•Engines like V8 (used in Chrome and Node.js) execute JavaScript.
•The engine parses, compiles, and executes the code.
2.Execution Contexts:
•Global Context: The default context when a script runs.
•Function Context: Created when a function is invoked.
•Block Context: Created with block-scoped constructs
like let, const.
3.Call Stack:
•Tracks the order of function calls.
•Last-in, first-out (LIFO) structure.
4.Event Loop and Callback Queue:
•Handles asynchronous operations using a queue and the event
loop.
Example:
•console.log("Start");
•setTimeout(() => console.log("Async Task"), 1000);
•console.log("End");
•
The Document Object Model (DOM)
The DOM is a programming interface for web documents. It represents the
structure of an HTML or XML document as a tree of nodes, where each node
corresponds to a part of the document.
1. Core Concepts
1.DOM Tree Structure:
•Root: document object.
•Nodes: Represent HTML elements, text, comments, etc.
2.Types of Nodes:
•Element Nodes: Represent HTML tags (e.g., <div>, <p>).
•Text Nodes: Represent text content inside elements.
•Attribute Nodes: Represent element attributes (e.g., class="example").
3.Navigating the DOM:
•document.querySelector(selector)
•document.getElementById(id)
•element.children (Direct child nodes).
DOM Manipulation:
•Changing element content:
javascript
const element = document.querySelector("h1"); element.textContent = "New Heading!";
•Modifying styles:
javascript
element.style.color = "blue";
•Adding/removing elements:
const newDiv = document.createElement("div");
newDiv.textContent = "Hello!";
document.body.appendChild(newDiv);
Event Handling in the DOM
Listening to Events:
Events: Clicks, keyboard presses, etc.
Add event listeners
const button = document.querySelector("button");
button.addEventListener("click", () => alert("Button Clicked!"));
• Event Bubbling and Capturing:
• Bubbling: Event propagates from child to parent.
• Capturing: Event propagates from parent to child.
• Example:
• document.body.addEventListener("click", () => console.log("Body clicked"),
true); // Capturing
Using DOM APIs for Interactive Web Pages
•Modifying Classes:
javascript
element.classList.add("highlight"); element.classList.remove("highlight");
•Handling Forms:
document.querySelector("form").addEventListener("submit", (event) =>
{ event.preventDefault(); console.log("Form Submitted!"); });
1. What Are Events?
Events are actions or occurrences that happen in the browser, such as user interactions (clicks,
keypresses) or system-generated events (page load, resize).
2. Handling Events
Event handling involves listening for specific events on DOM elements and defining what should
happen when the event occurs.
Basic Steps for Handling Events:
1.Select the target element.
2.Attach an event listener to the element.
3.Define the callback function (the action triggered by the event).
Adding Event Listeners
There are three common ways to handle events:
1.Inline Event Handlers (Not Recommended): Example:
html
<button onclick="alert('Clicked!')">Click Me</button>
2.Using DOM Properties: Example:
javascript
const button = document.querySelector("button"); button.onclick = () => alert("Button clicked!");
3.Using addEventListener (Preferred): Example:
javascript
const button = document.querySelector("button"); button.addEventListener("click", () => alert("Button clicked!"));
Handling Events from the <body> Element
The <body> element can also trigger various events, such as:
•onload: When the page finishes loading.
•onresize: When the window is resized.
•onclick: When a click occurs anywhere on the body.
Examples:
1.Page Load (onload):
html
<body onload="alert('Page loaded!')"> </body>
Or using JavaScript:
javascript
document.body.onload = () => alert("Page loaded!");
2.Handling Clicks on the Body:
javascript
document.body.addEventListener("click", (event) => { console.log(`You clicked at ($
{event.clientX}, ${event.clientY})`); });
3.Window Resize (onresize):
javascript
window.addEventListener("resize", () => { console.log("Window resized!"); });
5. Event Object
When an event occurs, an Event object is automatically passed to the callback function. It contains useful
information, such as:
•Event type: event.type
•Target element: event.target
•Mouse coordinates: event.clientX, event.clientY
•Prevent default behavior: event.preventDefault()
Example:
javascript
document.body.addEventListener("click", (event) => { console.log(`Clicked on: ${event.target.tagName}`);
console.log(`Mouse Position: (${event.clientX}, ${event.clientY})`); });
Event Propagation
Events in the DOM propagate in two phases:
1.Capturing Phase: The event travels from the root to the target element.
2.Bubbling Phase: The event travels back from the target element to the root.
Example of Capturing vs. Bubbling:
javascript
document.body.addEventListener( "click", () => console.log("Body clicked (capturing)"), true // Use capturing
phase ); document.body.addEventListener("click", () => console.log("Body clicked (bubbling)") ); // Default is
bubbling phase
7. Preventing Default Behavior
Some events have default actions (e.g., clicking a link navigates away, form submission reloads
the page). You can stop these actions with event.preventDefault().
Example:
javascript
document.querySelector("a").addEventListener("click", (event) => { event.preventDefault();
console.log("Link clicked but default action prevented!"); });
8. Stopping Event Propagation
If you want to stop an event from propagating (bubbling or capturing),
use event.stopPropagation().
Example:
javascript
document.querySelector("div").addEventListener("click", (event) => { console.log("Div clicked!");
event.stopPropagation(); }); document.body.addEventListener("click", () => console.log("Body
clicked!")); // Only "Div clicked!" will be logged when the div is clicked.
Working with Button, Text Box, and
Password Elements in HTML and JavaScript
•
HTML forms often use buttons, text boxes, and password fields for user interaction. JavaScript can enhance their functionality by
handling events and manipulating their properties.
• Button Elements
• HTML:
• Buttons are created using the <button> or <input> tags.
• html
• <!-- Button using <button> -->
• <button id="myButton">Click Me</button>
• <!-- Button using <input> -->
• <input type="button" id="myInputButton" value="Click Me Too">
•
const button = document.getElementById("myButton");
• button.addEventListener("click", () => {
• alert("Button was clicked!");
• });
2. Text Box Elements
HTML:
Text boxes are created using the <input> tag with the type="text" attribute:
html
<input type="text" id="myTextBox" placeholder="Enter your name">
JavaScript:
You can read and manipulate text box values:
javascript
const textBox = document.getElementById("myTextBox"); // Read the value console.log(textBox.value); // Set the value
textBox.value = "Default Text"; // Add an event listener for input changes textBox.addEventListener("input", () =>
{ console.log("Current Value: ", textBox.value); });
Password Elements
HTML:
Password fields are created using the <input> tag with the type="password" attribute:
html
<input type="password" id="myPassword" placeholder="Enter your password">
JavaScript:
Password fields can be manipulated similarly to text boxes:
javascript
const passwordBox = document.getElementById("myPassword"); // Read the password value console.log(passwordBox.value);
// Set a new password value (for testing purposes only!) passwordBox.value = "12345"; // Add an event listener
passwordBox.addEventListener("input", () => { console.log("Password Updated"); });
Form Submission with Buttons, Text Boxes, and Passwords
You can combine these elements in a form:
html
<form id="loginForm"> <input type="text" id="username" placeholder="Username"><br> <input
type="password" id="password" placeholder="Password"><br> <button
type="submit">Login</button> </form>
JavaScript:
Intercept form submission to handle login validation:
javascript
const form = document.getElementById("loginForm"); form.addEventListener("submit", (event) =>
{ event.preventDefault(); // Prevent default form submission const username =
document.getElementById("username").value; const password =
document.getElementById("password").value; if (username && password) { alert(`Logging in with
username: ${username}`); } else { alert("Please enter both username and password."); } });
• Additional Features and Enhancements
• Disabling Buttons:
• You can disable a button until some condition is met:
• const loginButton = document.querySelector("button");
• loginButton.disabled = true;
• document.getElementById("username").addEventListener("input", () => {
• loginButton.disabled = false; // Enable button when input changes
• });
• <input type="password" id="passwordField">
• <button id="togglePassword">Show</button>
• <script>
• const passwordField = document.getElementById("passwordField");
• const toggleButton = document.getElementById("togglePassword");
• toggleButton.addEventListener("click", () => {
• const isPassword = passwordField.type === "password";
• passwordField.type = isPassword ? "text" : "password";
• toggleButton.textContent = isPassword ? "Hide" : "Show";
• });
• </script>
• Introduction to Dynamic Documents
• Dynamic documents in web development refer to web
pages that can change content, style, or structure
interactively without requiring a page reload. This
interactivity is made possible through JavaScript and the
manipulation of the Document Object Model (DOM).
Key Concepts for Dynamic Documents
1.DOM Manipulation: JavaScript can dynamically modify HTML content, attributes, and styles. Example:
javascript
const header = document.getElementById("header"); header.textContent = "Welcome to Dynamic Documents!";
2.Event Handling: React to user actions (clicks, keystrokes, etc.) to create interactivity. Example:
javascript
const button = document.getElementById("changeColor"); button.addEventListener("click", () =>
{ document.body.style.backgroundColor = "lightblue"; });
3.Dynamic Styling: Change CSS properties programmatically. Example:
javascript
const box = document.getElementById("box"); box.style.border = "2px solid red";
4.Dynamic Content Loading: Fetch content from a server using AJAX or APIs and update the page dynamically.
Example:
javascript
fetch('https://api.example.com/data') .then(response => response.json()) .then(data =>
{ document.getElementById("content").textContent = data.message; });
Positioning Elements
Positioning defines how elements are placed on the web page. CSS provides several techniques for
controlling an element's position within a document.
CSS Positioning Types
1.Static Positioning (Default): Elements flow naturally in the document order.
css
div { position: static; }
2.Relative Positioning: An element is positioned relative to its normal position.
css
div { position: relative; top: 10px; /* Moves down by 10px */ left: 20px; /* Moves right by 20px */ }
3.Absolute Positioning: An element is positioned relative to its nearest positioned ancestor (not static).
css
div { position: absolute; top: 50px; left: 50px; }
4.Fixed Positioning: An element is positioned relative to the viewport and does not move when the page scrolls.
css
div { position: fixed; bottom: 0; right: 0; }
5.Sticky Positioning: An element toggles between relative and fixed depending on the scroll position.
css
div { position: sticky; top: 10px; /* Sticks 10px from the top */ }
Positioning Example
HTML:
html
<div id="static">Static</div> <div id="relative">Relative</div> <div id="absolute">Absolute</div> <div
id="fixed">Fixed</div>
CSS:
css
#static { position: static; } #relative { position: relative; top: 20px; left: 20px; background-color: lightblue; }
#absolute { position: absolute; top: 50px; left: 50px; background-color: lightgreen; } #fixed { position: fixed;
bottom: 10px; right: 10px; background-color: lightcoral; }
Combining Positioning with JavaScript
Dynamic positioning allows elements to move in response to user interactions:
javascript
const box = document.getElementById("movableBox"); document.addEventListener("mousemove",
(event) => { box.style.left = `${event.clientX}px`; box.style.top = `${event.clientY}px`; });
HTML:
html
<div id="movableBox" style="position: absolute; width: 50px; height: 50px; background-color:
blue;"></div>
•Title: Why Interactive Web Design?
•Content:
•Enhances user engagement.
•Simplifies complex interactions.
•Techniques covered:
1.Moving elements
2.Element visibility
3.Changing colors and fonts
4.Dynamic content
5.Stacking elements
6.Locating the mouse cursor
7.Reacting to a mouse click
8.Slow movement of elements
9.Drag-and-drop functionality.
Moving Elements
•Title: Animating Web Elements
•Content:
•What It Is: Creating movement to guide user attention or enhance aesthetics.
•Techniques:
•CSS animations (@keyframes) for predefined movements.
•JavaScript for dynamic, event-driven animations.
•Libraries like GSAP for complex animations.
•Example: Sliding navigation menu.
•Visual: GIF or demo showing an element moving from one side of the screen to another.
•Code Snippet Example:
@keyframes slideIn {
from { transform: translateX(-100%); }
to { transform: translateX(0); }
}
.menu { animation: slideIn 1s ease-in-out; }
Element Visibility
•Title: Showing and Hiding Elements
•Content:
•What It Is: Managing visibility to control user experience.
•Techniques:
•CSS properties: display, visibility, opacity.
•JavaScript methods: Toggling classes or styles.
•Use Case: Dropdown menus, tooltips.
•Visual: Before-and-after images of a hidden and visible element.
•Code Example:
•function toggleVisibility(element) {
• element.style.display = element.style.display === 'none' ? 'block' : 'none';
•}
Changing Colors and Fonts
•Title: Dynamic Styling
•Content:
•What It Is: Real-time updates to colors, fonts, and other styles.
•Techniques:
•CSS class switching (element.classList.toggle).
•JavaScript direct styling (element.style.color = 'red';).
•Example: Theme toggles or hover effects.
•Visual: Button changing colors on hover.
button.onmouseover = () => button.style.backgroundColor = 'blue';
Dynamic Content
•Title: Live Updates to Content
•Content:
•What It Is: Updating page content without reloading.
•Techniques:
•JavaScript DOM manipulation (innerHTML).
•Fetch API or AJAX for server-side data.
•Use Case: Newsfeed updates.
•Visual: Diagram of server-to-client content flow
Stacking Elements
•Title: Layering Web Elements
•Content:
•What It Is: Placing elements on top of each other using CSS.
•Technique:
•CSS z-index property to control stacking order.
•Use Case: Modals, popups.
•Visual: Stacked layers with visible z-index values.
.modal { z-index: 10; }
.background { z-index: 5; }
Locating the Mouse Cursor
•Title: Tracking Mouse Movement
•Content:
•What It Is: Capturing the mouse position on the screen.
•Technique:
•JavaScript mousemove event.
•Example: Interactive animations that follow the cursor.
•Visual: Diagram showing coordinates captured by a cursor.
Reacting to a Mouse Click
•Title: Click-Based Interactions
•Content:
•What It Is: Triggering actions in response to mouse clicks.
•Technique:
•JavaScript onclick events. Slide 10: Slow Movement of Elements
•Example: Expanding/collapsing a section. •Title: Smooth Transitions
•Visual: Demo of a button click triggering an animation. •Content:
•Code Example: •What It Is: Gradual animation for a polished look.
javascript •Techniques:
button.addEventListener('click', () => alert('Button clicked!')); •CSS transition property for timing.
•JavaScript for custom easing effects.
•Example: Sliding content panels.
•Visual: Animation of a slow-moving box.
•Code Example:
css
.box { transition: transform 2s; }
Dragging and Dropping Elements
•Title: Drag-and-Drop Interactions
•Content:
•What It Is: Allowing users to move items interactively.
•Techniques:
•HTML5 Drag-and-Drop API.
•Libraries like Interact.js for complex use cases.
•Example: File upload UI.
•Visual: Draggable element with a drop target.
•Code Example:
javascript
element.ondragstart = (e) => e.dataTransfer.setData('text', 'draggedItem');