0% found this document useful (0 votes)
3 views45 pages

Unit 3

Geolocation in HTML5 allows web pages to access a user's geographical location using GPS, Wi-Fi, or IP address, facilitating applications like maps and localized searches. It requires user permission, works across various devices, and is implemented easily with JavaScript. The document also discusses error handling in JavaScript, drag-and-drop functionality, and HTML5 Web Storage, highlighting their features, advantages, and disadvantages.

Uploaded by

devangdodiya6061
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views45 pages

Unit 3

Geolocation in HTML5 allows web pages to access a user's geographical location using GPS, Wi-Fi, or IP address, facilitating applications like maps and localized searches. It requires user permission, works across various devices, and is implemented easily with JavaScript. The document also discusses error handling in JavaScript, drag-and-drop functionality, and HTML5 Web Storage, highlighting their features, advantages, and disadvantages.

Uploaded by

devangdodiya6061
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

UNIT-3

What is Geolocation in HTML5?

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.

It’s useful for applications like:

● Maps and navigation (e.g., Google Maps)

● Weather updates based on location

● Localized search (e.g., “restaurants near me”)

● Location tagging on social media


Features of Geolocation
Feature Description

📍 Access to Location Can get latitude, longitude, altitude, and accuracy data.

📱 Device Compatibility Works on desktops, laptops, tablets, and smartphones.

🧭 Real-time Location Supports live tracking with watchPosition() method.

🔐 Permission Required Always asks the user for consent/permission before accessing location.

🛰 Uses Multiple Sources Works with GPS, Wi-Fi, IP address, cellular networks.

📦 Built-in API Uses navigator.geolocationobject – no need to install external libraries.

✅ Easy to Use Can be implemented with just a few lines of JavaScript.


Syntax (Using JavaScript with HTML5)

Syntax

navigator.geolocation.getCurrentPosition(successCallback, errorCallback)

● navigator.geolocation: The main object used to access the geolocation API.

● getCurrentPosition(): Method that asks the browser to get the user’s current
location.

● successCallback: Function that runs if the location is retrieved successfully.

● errorCallback (optional): Function that runs if there is an error (like permission


denied).
Example
<button onclick="getLocation()">Get Location</button>

<p id="demo"></p>

<script>

function getLocation() {

if (navigator.geolocation) {

navigator.geolocation.getCurrentPosition(function(position) {

document.getElementById("demo").innerHTML =

"Latitude: " + position.coords.latitude +

"<br>Longitude: " + position.coords.longitude;

});

} else {

document.getElementById("demo").innerHTML = "Geolocation is not supported by this browser.";

</script>
Advantages
Improves User Experience

● Can provide content or services based on user’s location (e.g., weather, maps).

Local Search Results

● Helps in finding nearby restaurants, shops, ATMs, etc.

Location-based Services

● Useful for ride-sharing apps, delivery tracking, and navigation.

Easy to Implement

● Built into HTML5, no need for plugins or third-party APIs.


Real-time Updates

● Can track location changes continuously using watchPosition().

Enhances Marketing

● Businesses can show personalized ads based on location.

Emergency Services

● Helpful for apps that provide location during emergencies.

No Server-Side Needed (Initial)

● Basic location access can be done entirely from the client side.
Disadvantages of Geolocation
Privacy Concerns

● Users may not feel comfortable sharing their location.

Requires User Permission

● App won’t work if the user denies access.

May Not Be Accurate Indoors

● GPS signals can be weak inside buildings.

Battery Consumption

● Continuous tracking can drain the device’s battery quickly.


Dependent on Network or Device

● Poor signal or old devices may give inaccurate or no location.

Security Risks

● If not handled properly, location data can be misused.

Only Works with Secure (HTTPS) Sites

● Geolocation API won't work over non-secure (HTTP) connections.

Browser Compatibility Limitations

● 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.

🧪 Helps Debugging Shows where and why the error happened.

📣 Improves User Experience Can show friendly messages instead of breaking.

⚙ 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

1. Stability Application continues to work even if some part fails.

2. User-friendly Users see helpful error messages instead of crashes.

3. Debugging Made Easier Developers can understand and fix bugs quickly.

4. Safer Code Prevents bugs from spreading or causing more problems.

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.

5. Slows Down Response Sometimes error handling adds delays in UI or logic.


Common Error Handling Techniques in JavaScript

Technique Use Case

try...catch For synchronous and async/await operations.

.catch() For handling rejected Promises.

if...else checks For validating data or checking conditions.

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.

With HTML5, implementing drag-and-drop functionality has become easier and


more streamlined, as it supports built-in drag-and-drop events. These events can
be applied to any element with minimal coding.
Drag and Drop Events
Events Description

Triggered when an element or text selection is being


ondrag
dragged.

Initiates the drag operation and specifies the data to be


ondragstart
dragged using drag(event).

Determines if the drop target will accept the drop. If


ondragenter
accepted, the event must be canceled.

Occurs when the mouse leaves the element before a


ondragleave
valid drop target is identified.

Specifies where the dragged data can be dropped, and


ondragover
prevents default behavior.

ondrop Fires when the dropped item lands in the target area.

ondragend Occurs after the drag operation is finished.


Features of Drag and Drop

Feature Description

🖱 Interactive Users can move elements visually using the mouse or touch.

🔁 Reusable Can be applied to images, text, cards, boxes, files, etc.

⚙ JavaScript-Based Uses dragstart, dragover, drop, etc. events.

📦 Customizable You can add animations, validations, and restrictions.

🔐 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.

Limited Touch Support (by default)


Needs extra handling for touch events on smartphones/tablets.
Main Elements of Drag and Drop

1. Draggable Element
● This is the item you want to drag (like an image, div, paragraph, etc.).

● You make it draggable by setting:

draggable="true"
Example:

<img id="drag1" src="img.png" draggable="true"


ondragstart="drag(event)">
2. Drop Target
● This is the container or area where you want to drop the
draggable item.

● Must handle ondragover and ondrop events.

🔹 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.

ondragover Needed to allow a drop. You must call event.preventDefault().

ondrop Fires when the element is dropped in the drop target.

ondragenter Fires when the dragged item enters the drop zone.

ondragleave Fires when the dragged item leaves the drop zone.

ondragend Fires after the drag operation ends.


4. DataTransfer Object

A special object used to store and transfer data while dragging.

It is used like this:


event.dataTransfer.setData("text", event.target.id);

Then retrieved during drop:

var data = event.dataTransfer.getData("text");


5. JavaScript Functions
Functions like drag(), drop(), and allowDrop() are used to control behavior.

🔹 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.

● Data is stored indefinitely (until explicitly deleted).

● Data is available even after closing and reopening the browser.

2. sessionStorage
● Used for temporary data storage.

● Data persists only during a page session.

● Once the tab or browser is closed, the data is cleared.


Features of HTML5 Web Storage
Feature Description

Key-Value Storage Data is stored as simple key-value pairs.

Storage Capacity Can store about 5–10 MB, which is much more than cookies (~4 KB).

Client-Side Only Data never automatically goes to the server.

JavaScript API Easily accessible and manageable using simple JavaScript commands.

Data Isolation Data is isolated by domain and protocol, preventing cross-site access.

No Expiry (localStorage) Data remains until manually cleared by code or user.

Session-based (sessionStorage) Data is deleted when the tab is closed.


Advantages of Web Storage

Larger Storage Capacity:

● Offers significantly more space than cookies.

Faster Access:

● Data is stored and retrieved quickly without involving the server.

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.

Storage is Tab-Specific (sessionStorage):

● sessionStorage is not shared across tabs/windows.

Data Loss:

● sessionStorage data is lost once the tab or window is closed.


Syntax and Usage
localStorage Example

// Store data

localStorage.setItem("username", "john_doe");

// Retrieve data

let user = localStorage.getItem("username");

// Remove specific item

localStorage.removeItem("username");

// Clear all storage

localStorage.clear();
sessionStorage Example

// Store data
sessionStorage.setItem("cartItem", "Apple");

// Retrieve data
let item = sessionStorage.getItem("cartItem");

// Remove specific item


sessionStorage.removeItem("cartItem");

// Clear all session storage


sessionStorage.clear();
Use Cases
Storing user preferences (like theme or language)

Saving items in a shopping cart (temporarily or persistently)

Keeping form data until submission

Storing game progress or quiz answers in browser-based applications


Application cache, updating cache, cache manifest file

Application Cache (AppCache) is an HTML5 feature that


allows web applications to store resources such as HTML
files, CSS, JavaScript, images, etc., in the browser. Once
cached, the application can be used offline, even without an
internet connection.
It works by specifying a manifest file that lists all the files the
browser should cache.
Components of Application Cache
1. Cache Manifest File

● 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>

<title>My Offline App</title>

</head>

<body>

<h1>Offline Mode Enabled</h1>

</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

CACHE: Lists all resources to be cached for offline use.

NETWORK: Resources that must be fetched online (e.g., API calls).

FALLBACK: Specifies fallback files if a resource is not accessible (e.g., offline.html).


Updating the Cache

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.

● Changes to cached resources alone won't trigger updates; the


manifest file must change.

● Once the update is available, the new cache is only applied after
the user reloads the page.
Features of Application Cache

Feature Description

Offline Browsing Enables access to web applications without an internet connection.

Automatic Updates Downloads updated files when the manifest file changes.

Performance Boost Cached files load faster than network resources.

File Management Allows the developer to specify exactly what gets cached and what doesn’t.

Granular Control Through NETWORK and FALLBACK sections in the manifest.


Applications of Application Cache

Offline Web Applications:

● Note-taking apps, to-do lists, calculators, etc.

Progressive Web Apps (Earlier PWAs):

● Before Service Workers, AppCache was used for offline-ready PWAs.

E-learning Platforms:

● Used to let users continue reading/studying even when offline.

News or Blogging Sites:

● Store articles for offline viewing.


Advantages of Application Cache
Offline Support:

● Users can access the application without internet connectivity.

Improved Performance:

● Cached files are loaded from the local disk, making them faster.

Bandwidth Saving:

● Reduces the need to repeatedly download static resources.

Automatic Caching:

● Once set up, it automatically handles caching and updates.

Simple to Implement:

● Just requires a manifest file and adding a reference to the HTML page.
Disadvantages of Application Cache
Deprecated Technology:

● AppCache is no longer supported in many modern browsers.

Difficult to Manage:

● Poor control over caching behavior, and errors are hard to debug.

Unpredictable Behavior:

● Sometimes updates don’t apply as expected until a full page reload.

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.

Automatic Resource Caching

● 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.

Granular Control via Manifest

● The manifest file provides control through three sections:


○ CACHE: — files to cache.
○ NETWORK: — files that must always be fetched online.
○ FALLBACK: — fallback resources when offline.

Reduced Server Load

● Once cached, the browser does not repeatedly request the same files, reducing server traffic.

Works Across Page Loads

● Cached data is retained even when the page is reloaded or the browser is restarted.
Summary

Aspect Description

Purpose To enable offline access to web apps using cached resources.

File Needed .manifest file listing resources to cache.

Key Features Offline access, caching, fallback resources.

Limitations Deprecated, inflexible, buggy, poor update control.

Modern Alternative Service Workers (recommended for all modern web apps).

You might also like