HTML5 APIs

2020-Apr-28

📚 start of w3schools HTML5 APIs

💨 by Eugene Ruthven

email Feedback About This Page

🔽 1. Geolocation 🔽 3. Web Storage ⬇️ 1. key() Method ⬇️ 4. setItem() Method
🔽 2. Drag and Drop   ⬇️ 2. length Property ⬇️ 5. removeItem() Method
🔽 4. Web Workers   ⬇️ 3. getItem() Method ⬇️ 6. clear() Method
🔽 5. SSE  

HTML Geolocation API

Used to locate user's position.

🚴 w3schools Geolocation API

Since this can compromise privacy, the position is not available unless the user approves it.

📝 Note: Geolocation is most accurate for devices with GPS, like smartphones.

📝 Note: As of Chrome 50, the Geolocation API will only work on secure contexts such as HTTPS. If your site is hosted on an non-secure origin (such as HTTP) the requests to get the users location will no longer function.

getCurrentPosition() method is used to return the user's position.

var x = document.getElementById("demo");

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else {
    x.innerHTML = "Geolocation is not supported by this browser.";
  }
}

function showPosition(position) {
  x.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude;
}

What above example shows:

from: MDN Web Docs
navigator.geolocation.getCurrentPosition(success[, error[, [options]])
🚴 MDN Web Docs Geolocation

The second parameter of the getCurrentPosition() method is used to handle errors. It specifies a function to run if it fails to get the user's location:

function showError(error) {
  switch(error.code) {
    case error.PERMISSION_DENIED:
      x.innerHTML = "User denied the request for Geolocation."
      break;
    case error.POSITION_UNAVAILABLE:
      x.innerHTML = "Location information is unavailable."
      break;
    case error.TIMEOUT:
      x.innerHTML = "The request to get user location timed out."
      break;
    case error.UNKNOWN_ERROR:
      x.innerHTML = "An unknown error occurred."
      break;
  }
}

To display the result in a map, you need access to a map service, like Google Maps.

Example:
function showPosition(position) {
  var latlon = position.coords.latitude + "," + position.coords.longitude;

  var img_url = "https://maps.googleapis.com/maps/api/staticmap?center=
  "+latlon+"&zoom=14&size=400x300&sensor=false&key=YOUR_KEY";

  document.getElementById("mapholder").innerHTML = "<img src='"+img_url+"'>";
}

getCurrentPosition() Method - Return Data

Returns an object on success.

Property Returned? Description
coords.latitude Always a decimal number
coords.longitude Always a decimal number
coords.accuracy Always the accuracy of position
coords.altitude if available altitude in meters above the mean sea level
coords.altitudeAccuracy if available altitude accuracy of position
coords.heading if available the heading as degrees clockwise from North
coords.speed if available the speed in meters per second
timestamp if available the date/time of the response

 

Other Interesting Methods
Method Description
watchPosition() Returns the current position of the user and continues
to return updated position as the user moves ie. the GPS in a car
clearWatch() Stops the watchPosition() method

HTML Drag and Drop API

🚴 w3schools Drag and Drop API

Drag and drop is a very common feature. It is when you grab an object and drag it to a different location.

In HTML, ANY ELEMENT can be dragged and dropped.

Example:
<script>
function allowDrop(ev) {
  ev.preventDefault();
}

function drag(ev) {
  ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text");
  ev.target.appendChild(document.getElementById(data));
}
</script>
</head>
<body>

<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>

<img id="drag1" src="img_logo.gif" draggable="true" ondragstart="drag(event)" width="336" height="69">

1. Make an Element Draggable

To make an element draggable, set the draggable attribute to true:
<img draggable="true">

2.What to Drag - ondragstart and setData()

Specify what should happen when the element is dragged.

dataTransfer.setData() method
Sets the data type and the value of the dragged data:

function drag(ev) {
  ev.dataTransfer.setData("text", ev.target.id);
}

3.Where to Drop - ondragover

ondragover event specifies where the dragged data can be dropped.

By default, data/elements cannot be dropped in other elements. To allow a drop, we must prevent the default handling of the element.

This is done by calling the event.preventDefault() method for the ondragover event:
event.preventDefault()

4. Do the Drop - ondrop

When the dragged data is dropped, a drop event occurs.

function drop(ev) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text");
  ev.target.appendChild(document.getElementByWhen the dragged data is dropped, a drop event occurs.Id(data));
}

Above code explained:

  1. Call preventDefault() to prevent the browser default handling of the data (default is open as link on drop)
  2. Get the dragged data with the dataTransfer.getData() method. This method will return any data that was set to the same type in the setData() method
  3. The dragged data is the id of the dragged element ("drag1")
  4. Append the dragged element into the drop element


HTML Web Storage API

😲 Better than cookies!!

⬇️ 1. key() Method ⬇️ 4. setItem() Method
⬇️ 2. length Property ⬇️ 5. removeItem() Method
⬇️ 3. getItem() Method ⬇️ 6. clear() Method

 

🚴 w3schools Web Storage API 🚴 w3schools Storage getItem() Method
🚴 w3schools The Storage Object 🚴 w3schools Storage setItem() Method
🚴 w3schools Storage key() Method 🚴 w3schools Storage removeItem() Method
🚴 w3schools Storage length Property 🚴 w3schools Storage clear() Method

Web applications can store data locally within the user's browser.

Web storage is more secure, and large amounts of data can be stored locally, without affecting website performance.

The storage limit is far larger than cookies - at least 5MB - and information is never transferred to the server.

Web storage is per origin - per domain and protocol. All pages, from one origin, can store and access the same data.

HTML web storage provides two objects for storing data on the client:
window.localStorage - stores data with no expiration date
window.sessionStorage - stores data for one session - data is lost when the browser tab is closed

Before using web storage, check browser support for localStorage and sessionStorage:

if (typeof(Storage) !== "undefined") {
  // Code for localStorage/sessionStorage.
} else {
  // Sorry! No Web Storage support..
}

localStorage Object

Stores the data with no expiration date.
The data will not be deleted when the browser is closed, and will be available the next day, week, or year.

// Store
localStorage.setItem("lastname", "Smith");

// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");

Create a localStorage name/value pair with name="lastname" and value="Smith"
Retrieve the value of lastname and insert it into the element with id="result"

or:

// Store
localStorage.lastname = "Smith";
// Retrieve
document.getElementById("result").innerHTML = localStorage.lastname;

The syntax for removing the lastname localStorage item is as follows:
localStorage.removeItem("lastname");

📝 Note: Name/value pairs are always stored as strings. Remember to convert them to another format when needed!

1. Storage key() Method    😲

Get the name of the first local storage item:
var x = localStorage.key(0);

Definition and Usage

The key() method returns name of the key with the specified index.

The key() method belongs to the Storage Object, which can be either:
a localStorage object
or
a sessionStorage object

Syntax

localStorage.key(index)
Or:
sessionStorage.key(index)

Parameter Values
Parameter   Description
index required a number representing the index of the key you want to get the name of

 

2. Storage length Property    😲

Example:
Get the number of local storage items for this domain:
var x = localStorage.length;

Definition and Usage

The length property returns the number of items stored in the browser's Storage Object, for this particular domain.

The length property belongs to the Storage Object, which can be either:
a localStorage object
or
a sessionStorrage object

Syntax

localStorage.length;
Or:
sessionStorage.length;

 

3. Storage getItem() Method    😲

Example
Get the value of the specified local storage item:
var x = localStorage.getItem("mytime");

Definition and Usage

The getItem() method returns value of the specified Storage Object item.

The getItem() method belongs to the Storage Object, which can be either:
a localStorage object
or
a sessionStorage object.

Syntax

localStorage.getItem(keyname)
Or
sessionStorage.getItem(keyname)

Parameter Values
Parameter   Description
keyname required a string specifying the name of the key you want to get the value of

 

4. Storage setItem() Method    😲

Example:
Set the value of the specified local storage item:
localStorage.setItem("mytime", Date.now());

Definition and Usage

The setItem() method sets the value of the specified Storage Object item.

The setItem() method belongs to the Storage Object, which can be either:
a localStorage object or a sessionStorage object

Syntax

localStorage.setItem(keyname, value)
Or:
sessionStorage.setItem(keyname, value)

Parameter Values
Parameter   Description
keyname required a string specifying the name of the key you want to get the value of
value required a string specifying the value of the key you want to set the value of

 

5. Storage removeItem() Method    😲

Example
Remove the the specified local storage item:
localStorage.removeItem("mytime");

Definition and Usage

The removeItem() method removes the specified Storage Object item.

The removeItem() method belongs to the Storage Object, which can be either:
a localStorage object
or
a sessionStorrage object

Syntax

localStorage.removeItem(keyname)
Or:
sessionStorage.removeItem(keyname)

Parameter Values
Parameter   Description
keyname required a string specifying the name of the item you want to remove

 

6. Storage clear() Method    😲

Remove all local storage items:
localStorage.clear();

The clear() method removes all the Storage Object item for this domain.

The clear() method belongs to the Storage Object, which can be either:
a localStorage object
or
a sessionStorrage object

Syntax

localStorage.clear()
Or
sessionStorage.clear()

Parameter Values

No parameters.

sessionStorage Object

Equal to the localStorage object, except that it stores the data for only one session.

😲 The data is deleted when the user closes the specific browser tab.

if (sessionStorage.clickcount) {
  sessionStorage.clickcount = Number(sessionStorage.clickcount) + 1;
} else {
  sessionStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " +
sessionStorage.clickcount + " time(s) in this session.";

HTML Web Workers API

A web worker is a JavaScript chunk running in the background, without affecting the performance of the page.

🚴 w3schools Web Workers API

Normally, when executing scripts in an HTML page, the page becomes unresponsive until the script is finished.

But a web worker is a JavaScript chunk that runs in the background, independently of other scripts, without affecting the performance of the page. You can continue to do whatever you want: clicking, selecting things, etc., while the web worker runs in the background.

1. Check Web Worker Support

Before creating a web worker, check whether the user's browser supports it:

if (typeof(Worker) !== "undefined") {
  // Yes! Web worker support!
  // Some code.....
} else {
  // Sorry! No Web Worker support..
}

2. Create a Web Worker File

A web worker is created in an external JavaScript file.

Example:
Create a script that counts and save it in demo_workers.js file:

var i = 0;

function timedCount() {
  i = i + 1;
  postMessage(i);
  setTimeout("timedCount()",500);
}

timedCount();

The important part of the code above is the postMessage() method - which is used to post a message back to the HTML page.

3. Create a Web Worker Object

When the web worker file exists, call it from an HTML page.

The following lines checks if the worker already exists, if not - it creates a new web worker object and runs the code in demo_workers.js:

if (typeof(w) == "undefined") {
  w = new Worker("demo_workers.js");
}

Messages can be sent to and received from the web worker.

Add an onmessage event listener to the web worker.

w.onmessage = function(event){
  document.getElementById("result").innerHTML = event.data;
};

When the web worker posts a message, the code within the event listener is executed. The data from the web worker is stored in event.data.

4. Terminate a Web Worker

When a web worker object is created, it will continue to listen for messages - even after the external script is finished - until it is terminated.

To terminate a web worker, and free browser/computer resources, use the terminate() method:

w.terminate();

5. Reuse the Web Worker

If the worker variable is set to undefined, after it has been terminated, the code can be reused:

w = undefined;

Web Workers and the DOM

Since web workers are in external files, they do not have access to the following JavaScript objects:
window
document
parent


HTML SSE API

Server-Sent Events (SSE) allow a web page to get updates from a server.

📚 w3schools SSE API

Server-Sent Events - One Way Messaging
A server-sent event is when a web page automatically gets updates from a server.

This was possible before, but the web page would have to ask if any updates were available. With server-sent events, the updates come automatically.

Examples:

Receive Server-Sent Event Notifications

The EventSource object is used to receive server-sent event notifications:

Example:
var source = new EventSource("demo_sse.php");
source.onmessage = function(event) {
  document.getElementById("result").innerHTML += event.data + "<br>";
};

Example explained:
  1. Create a new EventSource object, and specify the URL of the page sending the updates - in this example demo_sse.php
  2. Each time an update is received, the onmessage event occurs
  3. When an onmessage event occurs, put the received data into the element with id="result"

1. Check Server-Sent Events Support

In the 📚 w3schools Try it Yourself example associated with the above code chunk, there were some extra lines of code to check browser support for server-sent events.

if(typeof(EventSource) !== "undefined") {
  // Yes! Server-sent events support!
  // Some code.....
} else {
  // Sorry! No server-sent events support..
}

2. Server-Side Code Example

For the example above to work, the server has to be capable of sending data updates - like PHP or ASP.

The server-side event stream syntax is simple. Set the:
Content-Type
header to:
text/event-stream

Event Streams can now be started.

Code in PHP (demo_sse.php):
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

$time = date('r');
echo "data: The server time is: {$time}\n\n";
flush();
?>

Code in ASP (VB) (demo_sse.asp):
<%
Response.ContentType = "text/event-stream"
Response.Expires = -1
Response.Write("data: The server time is: " & now())
Response.Flush()
%>

Code explained:

  1. Set the Content-Type header to text/event-stream
  2. Specify that the page should not cache
  3. Output the data to send Always start with "data: "
  4. Flush the output data back to the web page

The EventSource Object
In the examples above the onmessage event is used to get messages. But other events are also available:


🏆 🎈 The End!!! 🏁 📣