An overview of JavaScript powered Web APIs that extend the functionality of the Web Browser
Curated by Kostas Minaidis | Updated: 04/07/2019
HTML5 can natively render video and audio in web pages using the <video> and <audio> HTML Media Elements.
Let's add a video:
<video src="trailer.mp4"></video>
<video src="https://video.com/trailer.mp4"></video>
Let's add some music:
<audio src="mozart.mp3"></audio>
<audio src="https://audio.com/mozart.mp3"></audio>
1) Opening <audio> tag
2) First audio source: mp3 file with appropriate MIME type attribute
"A media type (also known as a Multipurpose Internet Mail Extensions or MIME type) is a standard that indicates the nature and format of a document, file, or assortment of bytes."
3) Second audio source
4) Ready!
<audio controls>
<source src="audio.mp3" type="audio/mp3">
<source src="audio.ogg" type="audio/ogg">
</audio>
The Media API allows you to interact with the Media Elements. It acts as a middleman, offering a set of commands for observing and controlling the Media elements.
1) Create an HTML page
2) Add a <video></video> element (Use this source)
2.1) Add a poster attribute. (Use this source)
3) Add a <script></script> tag just before the closing </body> tag
4) Use document.querySelector()
to target the video element and store it in a variable named video
5) Use Media API methods
Methods:
video.play();
video.pause();
Combine setTimeout and play/pause
Combine the click event with play/pause
Challenge #1: apply background fade effect on play/pause
Challenge #2: Attach Play/Pause events directly on the video
Properties: ( Must be used with proper events )
video.duration;
video.currentTime; // GET
video.currentTime = 100; // SET
Full list of MediaElement Properties and Methods
canplay
play
pause
ended
loadeddata / loadedmetadata
Combine loadedmetadata
event with duration
property
timeupdate
Combine timeupdate
event with currentTime
property
Introduced with the HTML5 specification, the Drag and Drop API gives us the ability to drag elements from one place and drop them on other elements, much like our Operating Systems (Windows, Mac, Linux) and Desktop applications work.
1) Create a draggable Element and a drop target Element
2) Making an element draggable is as simple as setting the draggable attribute of an element to true
3) Setting an element as a drop target requires to disable the default dragover
behavior.
3.1) Get the drop element.
3.2) Define a function that will prevent the default dragover behavior.
3.3) Handle the drop event.
HTML
<div id="draggable" draggable="true"> Draggable Element </div>
<div id="drop-target"> Drop Target </div>
JavaScript
let dropTarget = document.querySelector("#drop-target");
function handleDragOver( event ){ event.preventDefault(); }
dropTarget.addEventListener( "dragover",handleDragOver );
dragstart
and drop
events to be handled.1) Store a reference of the draggable element in a variable
2) Handle the dragstart
event of the draggable element
2) Handle the drop
event of the drop element
JavaScript
// ...Code from Part 1/2
let draggable = document.querySelector("#draggable");
draggable.addEventListener( "dragstart", handleDragStart );
function handleDragStart(e){
console.log( e );
}
dropTarget.addEventListener( "drop", handleDrop );
function handleDrop(e){
console.log( e );
}
The DataTransfer
object holds the data that is being dragged during a drag and drop operation.
It holds one or more data items, each of one or more data types.
In its simplest form, transfering data from a draggable element to a drop target is a 2-step process:
dragstart
event using event.dataTransfer.setData( format, data )drop
event using event.dataTransfer.getData( format )1) Set some simple text data when the drag starts.
2) Access the data on the drop event.
JavaScript
// ...Code from Part 2/2
function handleDragStart(e){
e.dataTransfer.setData( "text/plain", "Some data" );
}
function handleDrop(e){
let data = e.dataTransfer.getData( "text/plain" );
}
Tasks
In Progress
Done
An easy to use API for accessing the browser's location.
For privacy
reasons, the user is asked for permission to report location information.
"Cartographers and geographers trace horizontal and vertical lines called latitudes and longitudes across Earth's surface to locate points on the globe."
"Together, they form the Earth’s geographical coordinates, and represent the angular distance of any location from the center of the Earth."
1)
Define a callback function that will handle the successful Geolocation retrieval
2)
Define a callback function that will handle errors
3)
Check to see if our browser supports the Geolocation API
4)
Use the getCurrentPosition
method to initiate the geolocation retrieval process
Remember: getCurrentPosition()
is an asynchronous function
5)
Handle browsers that do not support Geolocation
JavaScript
function geoSuccess( position ){
console.log( position );
}
function geoError( error ){
console.log( error.message );
}
if ( navigator.geolocation ) {
navigator.geolocation.getCurrentPosition( geoSuccess, geoError );
} else {
// Geolocation API Not Supported
}
geoSuccess(
position ){ ... }
geoError(
error ){ ... }
position: Object {
timestamp: [ date/time of the Response ],
coords: {
latitude: [ Latitude as decimal ],
longitude: [ Longitude as decimal ],
accuracy: [ Accuracy of position ],
altitude: [ Altitude in meters above sea level ],
speed: [ Speed in meters/second ],
}
}
error: Object {
code: [ 1-3 ],
message: [ String Error Description ]
}
OpenStreetMap (OSM):"A collaborative project to create a free editable map of the world. The data is free, and free of legal and technical restrictions."
OpenLayers: "OpenLayers is a JavaScript library which implements an API for developing dynamic map widgets on the web."
Notable method: watchPosition()
<canvas>
element in the webpage
<canvas>
drawing context
(2D,3D)
context
Object methods and properties to paint on the canvas
<canvas>
element in your webpageHTML
<canvas id="canvas" width="200" height="100"></canvas>
JavaScript
const canvas = document.querySelector("#canvas");
const context = canvas.getContext("2d");
context.fillRect( 0, 0, 200, 100 );
1)
Check if localStorage
is supported
2)
Store a key, value pair
3)
Retrieve a key value
4)
Get number of key/value pairs stored
5)
Get key value using index number
6)
Clear key/value pair
7)
Clear all key/value pairs
8)
Same rules apply for sessionStorage
Storage data can also be accessed through the Browser's Developer Tools. On Chrome, go to: Developer Tools > Application > Storage > Local Storage
JavaScript
if ( localStorage ){
localStorage.setItem( key, value );
localStorage.getItem( key );
localStorage.length;
localStorage.key( index );
localStorage.clearItem( key );
localStorage.clear();
}
if ( sessionStorage ){
sessionStorage.setItem( key, value );
}
Sources: [ Video | Poster Image ]