CodeToLive

HTML5 APIs

HTML5 introduces powerful APIs like Local Storage, Geolocation, and Canvas for advanced web development.

Local Storage

The localStorage API allows you to store data in the browser that persists even after the page is closed.


// Store data
localStorage.setItem("name", "Alice");

// Retrieve data
let name = localStorage.getItem("name");
console.log(name); // Output: Alice
      

Geolocation

The Geolocation API allows you to retrieve the user's geographical location.


navigator.geolocation.getCurrentPosition((position) => {
  console.log("Latitude:", position.coords.latitude);
  console.log("Longitude:", position.coords.longitude);
});
      

Canvas

The <canvas> element and its API allow you to draw graphics and animations directly in the browser.


<canvas id="myCanvas" width="200" height="100"></canvas>
<script>
  let canvas = document.getElementById("myCanvas");
  let ctx = canvas.getContext("2d");
  ctx.fillStyle = "red";
  ctx.fillRect(10, 10, 100, 50);
</script>
      

Web Workers

Web Workers allow you to run JavaScript in the background without blocking the main thread.


// main.js
let worker = new Worker("worker.js");
worker.postMessage("Start working!");

worker.onmessage = (event) => {
  console.log("Message from worker:", event.data);
};

// worker.js
self.onmessage = (event) => {
  console.log("Message from main:", event.data);
  self.postMessage("Work done!");
};
      
Back to Home