Unit 3
Unit 3
Geolocation in HTML5 is a feature that allows a web page to get the user’s geographical
location, such as latitude and longitude, using the device’s GPS, Wi-Fi, or IP address.
📍 Access to Location Can get latitude, longitude, altitude, and accuracy data.
🔐 Permission Required Always asks the user for consent/permission before accessing location.
🛰 Uses Multiple Sources Works with GPS, Wi-Fi, IP address, cellular networks.
Syntax
navigator.geolocation.getCurrentPosition(successCallback, errorCallback)
● getCurrentPosition(): Method that asks the browser to get the user’s current
location.
<p id="demo"></p>
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
document.getElementById("demo").innerHTML =
});
} else {
</script>
Advantages
Improves User Experience
● Can provide content or services based on user’s location (e.g., weather, maps).
Location-based Services
Easy to Implement
Enhances Marketing
Emergency Services
● Basic location access can be done entirely from the client side.
Disadvantages of Geolocation
Privacy Concerns
Battery Consumption
Security Risks
● While most modern browsers support it, older versions may not.
Handling Errors And Rejections
Error Handling:
It is the process of detecting, catching, and managing errors that happen
during code execution so that your program doesn't crash and can respond
properly.
Rejection Handling:
Rejections happen in Promises (asynchronous JavaScript operations) when
the operation fails. These are handled using .catch() or try...catch
with async/await.
Features of Error and Rejection Handling
Feature Explanation
✅ Prevents Program Crashes Catches errors and keeps the program running.
⚙ Works with Async Operations Works with Promises, async/await, APIs, and browser events.
🔒 Adds Safety to Applications Handles things like failed logins, missing data, permission issues, etc.
🔁 Allows Recovery from Errors Can retry operations or offer fallback options.
Advantages
Advantage Description
3. Debugging Made Easier Developers can understand and fix bugs quickly.
5. Handles Async Failures Deals with real-world failures like slow internet or server errors.
6. Supports Retry Logic Allows trying the same task again if it fails.
Disadvantages
Disadvantage Description
1. Extra Code Needed You have to write additional code to handle errors.
2. May Hide Real Bugs If not used properly, you may silently ignore important issues.
3. Overhead Too many try-catch blocks can make code harder to read.
4. Can Be Misused Improper use can lead to bad practices like ignoring all errors.
onerror event For handling errors in HTML/JavaScript events (like images not loading).
Drag and Drop elements
Drag and Drop is a very interactive and user-friendly concept that makes it easier
to move an object to a different location by grabbing it. This allows the user to click
and hold the mouse button over an element, drag it to another location, and
release the mouse button to drop the element there.
ondrop Fires when the dropped item lands in the target area.
Feature Description
🖱 Interactive Users can move elements visually using the mouse or touch.
🔐 Secure You can control what elements are draggable and droppable.
Advantages
Improves User Experience
Makes UI more interactive and engaging (like Trello or file uploads).
Easy to Implement
Uses simple HTML and JavaScript – no external libraries needed.
Customizable Behavior
You can control what can be dragged, where it can be dropped, etc.
Mobile-Friendly
Can be made responsive for touch devices with small tweaks.
Visual Feedback
You can highlight drop areas or animate the dragged elements.
Disadvantages
Browser Compatibility Issues
Might behave differently in older or less common browsers.
Accessibility Challenges
Harder for screen reader or keyboard-only users.
Performance Concerns
For complex items, dragging many elements can slow down the page.
Requires JavaScript
Pure HTML isn’t enough — JS is needed for handling the behavior.
1. Draggable Element
● This is the item you want to drag (like an image, div, paragraph, etc.).
draggable="true"
Example:
🔹 Example:
<div id="div1" ondrop="drop(event)"
ondragover="allowDrop(event)"></div>
3. Drag Events (JavaScript)
To handle drag and drop, you use the following JavaScript events:
Event Description
ondragstart Fires when the dragging starts. You usually set the data here.
ondragenter Fires when the dragged item enters the drop zone.
ondragleave Fires when the dragged item leaves the drop zone.
🔹 Example:
function allowDrop(event) {
event.preventDefault(); // allows drop
}
function drag(event) {
event.dataTransfer.setData("text", event.target.id);
}
function drop(event) {
event.preventDefault();
var data = event.dataTransfer.getData("text");
event.target.appendChild(document.getElementById(data));
}
What is HTML Web Storage?
HTML5 Web Storage is a mechanism that allows web applications to store data locally in the user's browser. Unlike
cookies, this data is not sent to the server with every HTTP request, making it more efficient for client-side data storage.
1. localStorage
● Used for persistent data storage.
2. sessionStorage
● Used for temporary data storage.
Storage Capacity Can store about 5–10 MB, which is much more than cookies (~4 KB).
JavaScript API Easily accessible and manageable using simple JavaScript commands.
Data Isolation Data is isolated by domain and protocol, preventing cross-site access.
Faster Access:
Simple API:
● Easy to use with just a few JavaScript methods (setItem(), getItem(), etc.).
Reduces Server Load:
● Since data isn’t sent with every request, it reduces unnecessary server
communication.
Persistence (localStorage):
● Keeps data even after the browser is closed, which is great for user preferences,
themes, etc.
Improved Security:
● Data is not sent via HTTP headers, reducing chances of data leakage.
Disadvantages of Web Storage
Not Encrypted:
● Data is stored in plain text and can be accessed through browser developer tools.
Synchronous API:
● Blocking in nature — reading or writing a large amount of data might slow the UI.
Limited Size:
● Though bigger than cookies, it still has limits (usually 5–10MB depending on the browser).
No Server-Side Access:
● Data is available only on the client side; can't be accessed by the server directly.
Data Loss:
// Store data
localStorage.setItem("username", "john_doe");
// Retrieve data
localStorage.removeItem("username");
localStorage.clear();
sessionStorage Example
// Store data
sessionStorage.setItem("cartItem", "Apple");
// Retrieve data
let item = sessionStorage.getItem("cartItem");
● A plain text file that tells the browser which files to cache.
● Linked to the HTML file using the manifest attribute in the <html> tag.
<!DOCTYPE html>
<html manifest="offline.manifest">
<head>
</head>
<body>
</body>
</html>
2. Structure of Manifest File
CACHE MANIFEST
# Version 1.0
CACHE:
index.html
style.css
script.js
logo.png
NETWORK:
FALLBACK:
Sections:
Section Purpose
To update the application cache, the browser checks the manifest file:
● If the manifest file has changed (even a comment or version number),
it downloads all files again.
● Once the update is available, the new cache is only applied after
the user reloads the page.
Features of Application Cache
Feature Description
Automatic Updates Downloads updated files when the manifest file changes.
File Management Allows the developer to specify exactly what gets cached and what doesn’t.
E-learning Platforms:
Improved Performance:
● Cached files are loaded from the local disk, making them faster.
Bandwidth Saving:
Automatic Caching:
Simple to Implement:
● Just requires a manifest file and adding a reference to the HTML page.
Disadvantages of Application Cache
Deprecated Technology:
Difficult to Manage:
● Poor control over caching behavior, and errors are hard to debug.
Unpredictable Behavior:
Security Risks:
● Cached data can be exposed if not properly managed, especially sensitive information.
All-or-Nothing Caching:
● If one file fails to cache, none of the files are cached (atomic caching).
Lack of Flexibility:
Features of Application Cache
Offline Access
● Allows web applications to work without an internet connection by caching necessary files locally.
● Resources listed in the manifest file are automatically downloaded and cached by the browser.
Faster Loading
● Cached files are served from the local storage, making page load times significantly faster.
Data Persistence
● Cached resources remain stored until explicitly cleared by the browser or application logic.
Defined Cache Management
● Developers can specify exactly which files to cache, which to always fetch online, and fallback resources using a manifest file.
Automatic Updates
● When the manifest file changes (even slightly), the browser automatically updates the cached resources.
● Once cached, the browser does not repeatedly request the same files, reducing server traffic.
● Cached data is retained even when the page is reloaded or the browser is restarted.
Summary
Aspect Description
Modern Alternative Service Workers (recommended for all modern web apps).