Loading lessons...
Geolocation and Popups
Geolocation and Popups
Two more handy browser APIs: finding location and showing message boxes.
Geolocation
navigator.geolocation finds the user's position (with permission):
navigator.geolocation.getCurrentPosition(
function(position) {
console.log(position.coords.latitude);
console.log(position.coords.longitude);
},
function(error) {
console.log("Location denied");
}
);
Popup boxes
JavaScript has three built-in dialogs:
- alert(): a message box with OK.
- confirm(): asks OK or Cancel, returns true/false.
- prompt(): asks for text input.
alert("Hello");
let ok = confirm("Are you sure?");
let name = prompt("What is your name?");
When to use popups
Popups block the page and can be annoying, so use them sparingly. Custom dialogs and forms are usually nicer.
The navigator object
navigator describes the browser and system:
navigator.userAgent;
navigator.language;
TL;DR
- Geolocation gets the user's position with permission.
- alert, confirm, and prompt are built-in popups.
- Use popups sparingly.
- navigator describes the browser.