Skip to content
HTML APIs Explained — Geolocation, Storage, Drag & Drop & More

HTML APIs Explained — Geolocation, Storage, Drag & Drop & More

DodaTech Updated Jun 6, 2026 10 min read

HTML APIs are built-in browser tools that let JavaScript interact with the device and browser environment — getting the user’s location, saving data on their computer, dragging elements around the page, running code in the background, and receiving live updates from a server.

What You’ll Learn

By the end of this tutorial, you’ll be able to get a user’s geographic location (with permission), store data in the browser with localStorage and sessionStorage, make elements draggable with Drag & Drop, run background tasks with Web Workers, and receive real-time server updates with Server-Sent Events.

Prerequisite: You should understand JavaScript basics. HTML JavaScript covers what you need.

Where This Fits in Your Learning Path

    flowchart LR
    A["Video, Audio & Media"] --> B["**HTML APIs**"]
    B --> C["Semantic HTML"]
    C --> D["HTML & SEO"]
    D --> E["Frontend-Ready Developer"]
    style B fill:#f97316,stroke:#c2410c,color:#fff
    style A fill:#e5e7eb,stroke:#9ca3af,color:#374151
    style E fill:#22c55e,stroke:#16a34a,color:#fff
  

Geolocation API — Where Is the User?

The Geolocation API lets you ask the browser: “Where is this user right now?” The browser then asks the user for permission (required by all browsers for privacy).

<button onclick="getLocation()">Find My Location</button>
<p id="geo-demo"></p>

<script>
  function getLocation() {
    // Step 1: Check if the browser supports Geolocation
    if (!navigator.geolocation) {
      document.getElementById('geo-demo').textContent =
        'Geolocation is not supported by this browser.';
      return;
    }

    // Step 2: Ask the user for their location
    navigator.geolocation.getCurrentPosition(
      // Success callback: runs when we get the location
      function(position) {
        const lat = position.coords.latitude.toFixed(4);
        const lon = position.coords.longitude.toFixed(4);
        document.getElementById('geo-demo').textContent =
          'Latitude: ' + lat + ', Longitude: ' + lon;
      },
      // Error callback: runs if something goes wrong
      function(error) {
        document.getElementById('geo-demo').textContent =
          'Error getting location: ' + error.message;
      }
    );
  }
</script>

Understanding How This Works

  • navigator.geolocation is a built-in browser object (no libraries needed)
  • getCurrentPosition() takes two functions:
    • Success function — receives a position object with coords.latitude and coords.longitude
    • Error function — receives an error object if the user denies permission, location is unavailable, or the request times out

Geolocation Methods

MethodWhen to Use It
getCurrentPosition()Get location once (e.g., “Find nearest store”)
watchPosition()Continuously track location (e.g., fitness tracker, delivery map)
clearWatch(id)Stop tracking (pass the ID returned by watchPosition)

Real-world use: Food delivery apps use geolocation to find nearby restaurants. Navigation apps track your position as you move. Weather sites show your local forecast.

Security note: Always ask for location in response to a user action (button click), not on page load. Users are suspicious of sites that request location immediately. Explain why you need it. This is also a GDPR/privacy best practice.


Web Storage API — Saving Data in the Browser

Web Storage lets you save data in the user’s browser so it persists after page reloads — like a tiny database for each website.

localStorage vs sessionStorage

FeaturelocalStoragesessionStorage
LifetimeUntil the user clears itUntil the tab or browser closes
Size Limit~5-10 MB per origin~5-10 MB per origin
ScopeShared across all tabs/windows of the same siteOnly in the current tab
Use CaseTheme preference, saved itemsForm data in progress, temporary state

Saving and Reading Data

<script>
  // SAVE data
  localStorage.setItem('theme', 'dark');
  sessionStorage.setItem('formStatus', 'in-progress');

  // READ data
  const theme = localStorage.getItem('theme');
  console.log(theme); // Output: "dark"

  // REMOVE one item
  localStorage.removeItem('theme');

  // CLEAR everything for this site
  // localStorage.clear();
</script>

How it works: Data is stored as key-value pairs (both must be strings). Think of it like a labeled box in a closet: setItem("theme", "dark") puts “dark” in the box labeled “theme”. getItem("theme") opens the box and reads what’s inside.

Storing Objects (JSON)

Since storage only accepts strings, you need JSON.stringify and JSON.parse for objects:

<script>
  // Save an object
  const user = { name: 'Alice', score: 42 };
  localStorage.setItem('user', JSON.stringify(user));

  // Read it back
  const saved = JSON.parse(localStorage.getItem('user'));
  console.log(saved.name); // Output: "Alice"
</script>

Why JSON? localStorage can only store strings. If you try localStorage.setItem('user', user) without JSON.stringify, you’ll save "[object Object]" — useless. JSON.stringify converts the object to a string, and JSON.parse converts it back.

Security note: Never store sensitive data (passwords, tokens, credit card info) in localStorage. It’s accessible to any JavaScript running on the page, including third-party scripts loaded from CDNs. Use HttpOnly cookies for sensitive data, or server-side sessions.


Drag & Drop API

The Drag & Drop API lets users click and drag elements across the page — like dragging files into a folder on your desktop.

How Drag & Drop Works

There are four steps:

  1. Mark an element as draggable: Add draggable="true"
  2. Start the drag: ondragstart saves data about what’s being dragged
  3. Allow the drop: ondragover must call preventDefault() to allow dropping
  4. Handle the drop: ondrop receives the dragged data and does something with it
<style>
  .box {
    width: 100px; height: 100px;
    background: #667eea; color: white;
    display: flex; align-items: center; justify-content: center;
    border-radius: 8px; cursor: grab;
  }
  .zone {
    width: 200px; height: 150px;
    border: 3px dashed #ccc;
    border-radius: 12px;
    display: flex; align-items: center; justify-content: center;
    margin-top: 16px;
  }
</style>

<div class="box" draggable="true" id="drag1"
     ondragstart="event.dataTransfer.setData('text/plain', event.target.id)">
  Drag me
</div>

<div class="zone" ondrop="handleDrop(event)" ondragover="event.preventDefault()">
  Drop here
</div>

<script>
  function handleDrop(event) {
    event.preventDefault();
    const id = event.dataTransfer.getData('text/plain');
    event.target.textContent = 'Dropped ' + id + '!';
    event.target.style.borderColor = '#667eea';
  }
</script>

Understanding Each Step

StepAttributeWhat happens
1draggable="true"Tells the browser this element can be dragged
2ondragstartFires when dragging begins. We save the element’s ID into the drag data
3ondragoverFires when dragging over the drop zone. We call preventDefault() to allow dropping
4ondropFires when the user releases the mouse. We get the saved data and update the UI

Real-world use: File upload areas (drag files from desktop), kanban boards (drag tasks between columns), reorderable lists (drag items up/down), and shopping cart drag-to-add.


Web Workers — Background JavaScript

JavaScript normally runs on the main thread — the same thread that handles UI rendering and user interactions. If your JavaScript takes too long (like a complex calculation), the page freezes and the user can’t click anything.

Web Workers solve this by running JavaScript in a background thread:

<!-- index.html -->
<script>
  // Create a worker from a separate JS file
  const worker = new Worker('worker.js');

  // Send a message to the worker
  worker.postMessage('Start calculating!');

  // Listen for messages from the worker
  worker.onmessage = function(event) {
    console.log('Received from worker:', event.data);
  };
</script>
// worker.js — runs in the background
onmessage = function(event) {
  console.log('Worker received:', event.data);

  // Do something CPU-intensive here
  let result = 0;
  for (let i = 0; i < 1000000000; i++) {
    result += i;
  }

  // Send the result back
  postMessage('Calculation result: ' + result);
};

What Workers CAN and CANNOT Do

CAN doCANNOT do
Math calculationsAccess the DOM (document)
Fetch data (AJAX)Access window or parent
Use setTimeout/setIntervalAccess localStorage
Import other scripts (importScripts)Update the UI directly

Why the restrictions? Workers run in a completely separate environment from the main page. They can’t access the DOM because the DOM belongs to the main thread. If two threads tried to modify the DOM at the same time, you’d get crashes and impossible-to-debug bugs.

Real-world use: Image processing (applying filters), real-time data analysis, syntax highlighting in code editors (like VS Code), and game physics calculations.


Server-Sent Events (SSE) — Live Updates from the Server

Server-Sent Events let the server push updates to the browser automatically — like a live news feed or stock ticker.

<script>
  if (typeof EventSource !== 'undefined') {
    // Connect to the SSE endpoint
    const source = new EventSource('updates.php');

    // Handle incoming messages
    source.onmessage = function(event) {
      document.getElementById('updates').textContent =
        'Latest update: ' + event.data;
    };

    // Handle errors
    source.onerror = function() {
      console.log('Connection lost. Will auto-reconnect...');
    };
  } else {
    console.log('SSE not supported in this browser.');
  }
</script>

How it works: The browser opens a persistent HTTP connection to the server. The server sends data whenever it has new information, and the connection stays open. If the connection drops, the browser automatically reconnects.

Why SSE and not WebSockets? SSE is simpler — it’s one-directional (server to client only) and works over regular HTTP. WebSockets are bidirectional (client and server can both send) but are more complex. Use SSE for things like live notifications, news feeds, and status updates. Use WebSockets for chat apps and collaborative editing.


Common HTML API Mistakes

1. Not Checking for API Support

// ❌ Wrong: assumes Geolocation exists
navigator.geolocation.getCurrentPosition(success, error);

// ✅ Correct: check first, provide fallback
if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(success, error);
} else {
  showFallbackMessage();
}

2. Forgetting event.preventDefault() on Drag Over

<!-- ❌ Wrong: drop event never fires -->
<div ondrop="handleDrop(event)" ondragover="console.log('hovering')">

<!-- ✅ Correct: preventDefault allows the drop -->
<div ondrop="handleDrop(event)" ondragover="event.preventDefault()">

Why? By default, the browser doesn’t allow dropping. preventDefault() tells the browser “yes, this is a valid drop target.”

3. Storing Sensitive Data in localStorage

// ❌ Wrong: passwords in localStorage
localStorage.setItem('password', 'supersecret123');

// ✅ Correct: use HttpOnly cookies for sensitive data (server-side only)
// localStorage is accessible to any JS on the page

4. Trying to Access the DOM from a Worker

// worker.js
onmessage = function() {
  document.body.style.backgroundColor = 'red'; // ❌ Error!
};

Workers can’t touch the DOM. They must send data back to the main thread via postMessage, and the main script updates the UI.

5. Not Handling Geolocation Permission Denial

Users can deny location access. Always handle the error with a helpful message rather than just failing silently.


Try It Yourself

Test Web Storage and Drag & Drop:

▶ Try It Yourself Edit the code and click Run

Common Mistakes Beginners Make

1. Skipping the Fundamentals

Many beginners jump straight to advanced topics without mastering the basics. Take time to understand the core concepts before moving on.

2. Not Practicing Enough

Reading tutorials without writing code leads to shallow understanding. Code along with every example and experiment on your own.

3. Ignoring Error Messages

Error messages tell you exactly what went wrong. Read them carefully — they usually point to the line and type of issue.

4. Copy-Pasting Without Understanding

It’s tempting to copy code from tutorials, but typing it yourself and understanding each line builds real skill.

5. Giving Up Too Early

Every developer hits frustrating bugs. Take breaks, ask for help, and remember that struggling is part of learning.

Practice Questions

Q1: What method do you call to save data in localStorage?

localStorage.setItem('key', 'value') — both key and value must be strings.

Q2: Why must you call event.preventDefault() in ondragover for drag and drop?

Browsers prevent dropping by default. preventDefault() tells the browser this element allows drops.

Q3: What’s the difference between localStorage and sessionStorage?

localStorage persists until manually cleared, even after closing the browser. sessionStorage is cleared when the tab is closed.

Q4: Why can’t Web Workers access the DOM?

Workers run on a separate thread. If two threads modified the DOM simultaneously, it would cause crashes and data corruption. Workers communicate via messages instead.

Q5: What happens when a user denies geolocation permission?

The error callback fires with an error object. You should show a helpful message explaining why location was needed and how to enable it.

Challenge

Build a “Todo List” app using localStorage:

  • Input field + “Add” button to add tasks
  • Each task has a “Delete” button
  • On page reload, all tasks should still be visible (loaded from localStorage)
  • Style it cleanly

Frequently Asked Questions

Is localStorage secure?
No. Any JavaScript on the page can access it, including third-party scripts. Never store passwords, tokens, or credit card info. Use HttpOnly cookies for sensitive data.
What happens when localStorage is full?
The browser throws a QuotaExceededError. Always wrap setItem in a try/catch if you’re storing large amounts of data.
When should I use Web Workers vs Server-Sent Events?
Workers are for CPU-heavy JavaScript tasks (calculations, data processing). SSE is for receiving live data from a server. They solve completely different problems.

What’s Next?

Now learn semantic HTML and SEO:

What’s Next

Congratulations on completing this Html Apis tutorial! Here’s where to go from here:

  • Practice daily — Consistency is more important than long study sessions
  • Build a project — Apply what you learned by building something real
  • Explore related topics — Check out other tutorials in the same category
  • Join the community — Discuss with other learners and share your progress

Remember: every expert was once a beginner. Keep coding!

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro