email Feedback About This Page
Used to locate user's position.
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+"'>"; }
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 |
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">
To make an element draggable, set the draggable attribute to true:
<img draggable="true">
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); }
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()
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:
😲 Better than cookies!!
⬇️ 1. key() Method | ⬇️ 4. setItem() Method |
⬇️ 2. length Property | ⬇️ 5. removeItem() Method |
⬇️ 3. getItem() Method | ⬇️ 6. 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.. }
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!
Get the name of the first local storage item:
var x = localStorage.key(0);
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
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 |
Example:
Get the number of local storage items for this domain:
var x = localStorage.length;
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
localStorage.length;
Or:
sessionStorage.length;
Example
Get the value of the specified local storage item:
var x = localStorage.getItem("mytime");
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.
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 |
Example:
Set the value of the specified local storage item:
localStorage.setItem("mytime", Date.now());
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
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 |
Example
Remove the the specified local storage item:
localStorage.removeItem("mytime");
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
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 |
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
localStorage.clear()
Or
sessionStorage.clear()
No parameters.
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.";
A web worker is a JavaScript chunk running in the background, without affecting the performance of the page.
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.
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.. }
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.
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.
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();
If the worker variable is set to undefined, after it has been terminated, the code can be reused:
w = undefined;
Since web workers are in external files, they do not have access to the following JavaScript objects:
window
document
parent
Server-Sent Events (SSE) allow a web page to get updates from a server.
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:
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>"; };
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.. }
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(); ?>
<% Response.ContentType = "text/event-stream" Response.Expires = -1 Response.Write("data: The server time is: " & now()) Response.Flush() %>
Code explained:
The EventSource Object
In the examples above the onmessage event is used to get messages. But other events are also available: