← Back to Tutorials Chapter 9

APIs & Advanced Features

Geolocation API

Access the user's geographic location (with permission):

<button onclick="getLocation()">Show My Location</button>
<p id="location-output"></p>

<script>
  function getLocation() {
    if (!navigator.geolocation) {
      document.getElementById('location-output').textContent =
        'Geolocation is not supported by your browser.';
      return;
    }

    navigator.geolocation.getCurrentPosition(
      function(position) {
        const { latitude, longitude } = position.coords;
        document.getElementById('location-output').innerHTML =
          `Latitude: ${latitude}<br>Longitude: ${longitude}`;
      },
      function(error) {
        document.getElementById('location-output').textContent =
          'Error: ' + error.message;
      }
    );
  }
</script>
Privacy: Browsers always ask for user permission before sharing location data.

Drag and Drop API

Make elements draggable using native HTML5 drag-and-drop:

<div id="drag-source" draggable="true" ondragstart="drag(event)" style="width:100px;height:100px;background:blue;color:#fff;display:flex;align-items:center;justify-content:center;">
  Drag me
</div>

<div id="drop-zone" ondrop="drop(event)" ondragover="allowDrop(event)" style="width:200px;height:200px;border:2px dashed #333;margin-top:10px;display:flex;align-items:center;justify-content:center;">
  Drop here
</div>

<script>
  function allowDrop(e) { e.preventDefault(); }
  function drag(e) { e.dataTransfer.setData('text', e.target.id); }
  function drop(e) {
    e.preventDefault();
    const data = e.dataTransfer.getData('text');
    e.target.appendChild(document.getElementById(data));
  }
</script>

Web Storage API

Store data in the browser with localStorage (persists) and sessionStorage (per tab):

<!-- Saving user preferences -->
<input type="text" id="username" placeholder="Enter your name">
<button onclick="saveName()">Save</button>
<p id="greeting"></p>

<script>
  // Load saved data on page load
  window.onload = function() {
    const name = localStorage.getItem('username');
    if (name) {
      document.getElementById('greeting').textContent = 'Hello, ' + name + '!';
      document.getElementById('username').value = name;
    }
  };

  function saveName() {
    const name = document.getElementById('username').value;
    localStorage.setItem('username', name);
    document.getElementById('greeting').textContent = 'Hello, ' + name + '!';
  }

  // sessionStorage works the same but clears when tab closes
  // sessionStorage.setItem('key', 'value');
  // sessionStorage.getItem('key');
  // sessionStorage.removeItem('key');
  // sessionStorage.clear();
</script>

History API

Manipulate the browser's session history without page reloads:

<button onclick="pushState()">Push State</button>
<button onclick="goBack()">Go Back</button>

<script>
  function pushState() {
    history.pushState({ page: 2 }, 'Page 2', '?page=2');
    document.title = 'Page 2';
  }

  window.onpopstate = function(e) {
    alert('You navigated back! State: ' + JSON.stringify(e.state));
  };

  function goBack() {
    history.back();
  }
</script>

Fetch API

Make HTTP requests to fetch data from APIs:

<button onclick="loadData()">Load Users</button>
<ul id="user-list"></ul>

<script>
  async function loadData() {
    try {
      const response = await fetch('https://jsonplaceholder.typicode.com/users');
      if (!response.ok) throw new Error('Network error');
      const users = await response.json();
      const list = document.getElementById('user-list');
      list.innerHTML = users.slice(0, 5).map(user =>
        `<li>${user.name} (${user.email})</li>`
      ).join('');
    } catch (error) {
      alert('Failed to load data: ' + error.message);
    }
  }
</script>

Notifications API

<button onclick="showNotification()">Show Notification</button>

<script>
  function showNotification() {
    if (!('Notification' in window)) {
      alert('Notifications not supported.');
      return;
    }

    if (Notification.permission === 'granted') {
      new Notification('Hello!', {
        body: 'This is a notification from your HTML page.',
        icon: 'images/icon.png'
      });
    } else if (Notification.permission !== 'denied') {
      Notification.requestPermission().then(permission => {
        if (permission === 'granted') showNotification();
      });
    }
  }
</script>

Practice Task

Build a simple "Notes App" page that: