JavaScript APIs and Libraries

37
Slide 1 Joan Boone [email protected] INLS 572 Web Development JavaScript Application Programming Interfaces (APIs) and Libraries

Transcript of JavaScript APIs and Libraries

Page 1: JavaScript APIs and Libraries

Slide 1

Joan Boone

[email protected]

INLS 572Web Development

JavaScript Application Programming

Interfaces (APIs) and Libraries

Page 2: JavaScript APIs and Libraries

Slide 2

Part 1: Overview

Part 2: Video

Part 3: Audio

Part 4: Maps

Part 5: Charts

Part 6: W3.CSS and Slideshows

Page 3: JavaScript APIs and Libraries

Slide 3

What are APIs ?

• Provide building blocks of code that simplify the interface to complex functions by abstracting away the underlying details

• Provide common, frequently needed functions that allow developers to reuse existing code

Source: MDN Web Docs: Introduction to Web APIs

JavaScript (client-side) has many APIs that fall into 2 categories

• Browser APIs that are built into your browser, e.g., DOM API

• Third party APIs – not built into your browser, and you need to access the code and documentation from the vendor's website.

Application Programming Interfaces are collections of code and tools that are available in all programming languages, and that allow developers to create complex functionality more easily.

Page 4: JavaScript APIs and Libraries

Slide 4

What can APIs do?Just about anything you need them to do: MDN Web APIs

Most common categories of browser APIs include DOM APIs for manipulating HTML and CSS

Fetching data from the server using XMLHttpRequest or Fetch API, and returning data in XML or JSON format

Drawing and manipulating graphics (Canvas, WebGL)

Audio and Video APIs that allow you to customize user interfaces

Device APIs to access device features such as GPS, camera, orientation, vibration

Client-side storage APIs that enable offline app use, and saving state of apps between page loads.

Many third-party APIs: Social media, news, open data, ...

Source: MDN Web Docs: Introduction to Web APIs

Page 5: JavaScript APIs and Libraries

Slide 5

DOM APIs that we've already used to access and modify HTML content and style

Accessing HTML content var dateElement = document.querySelector("#todays-date");

Modifying HTML content dateElement.textContent = todaysDate;

dateElement.textContent = todaysDate.toDateString();

Modifying styles of HTML content dateElement.style.fontStyle = “italic”;

details.style.display = “none”;

Adding a click event to HTML element logo.addEventListener('click', changeLogo);

moreLess.addEventListener('click', toggleContent);

Page 6: JavaScript APIs and Libraries

Slide 6

JavaScript Libraries Libraries, in any programming language, are typically a collection of files that contain functions. In JavaScript libraries, these are functions that you can reference in your web page, and have the advantages of

• Simplifying coding by providing functions for common tasks

• Reusing existing code that has already been tested

• Enabling faster development

Source: MDN Web Docs: Introduction to Web APIs

Frameworks are a “next step up” from libraries because they tend to be packages of HTML, CSS, and JavaScript that you install and use to build web applications.

The key difference between a library and framework is “Inversion of Control”. When calling a method from a library, the developer is in control. With a framework, the control is inverted: the framework calls the developer's code.

Your JavaScript can use these library functions by calling them via a documented interface, or an application programming interface (API).

Page 7: JavaScript APIs and Libraries

Slide 7

Using JavaScript Libraries There are many free libraries available

How to use them? Generally, they are all structured in a similar way.• First, review the demos and examples to see if the library

has the functionality you are looking for

• Download the examples, and find one that is similar to what you want to do. Understand how it works!

• Link to, or download, the JavaScript and CSS files used by the library

• Modify the example code (or write your own version)

• Check the documentation for ways to customize the code

Page 8: JavaScript APIs and Libraries

Slide 8

Part 1: Overview

Part 2: Video

Part 3: Audio

Part 4: Maps

Part 5: Charts

Part 6: W3.CSS and Slideshows

Page 9: JavaScript APIs and Libraries

Slide 9

HTML Video & Audio• Video and Audio can be embedded in your HTML. These

elements have a browser API that provides built-in support for audio and visual elements that does not require the use of plug-ins (e.g., Flash), but may require some scripting for customization

• Elements <video> element embeds a video on a web page

<audio> element embeds an audio file on a web page

Many attributes can be modified with JavaScript

• autoplay, controls, loop, preload, src, height, width, muted

Default controls: play/pause, mute, volume control, progress bar

• MDN Web Docs: Audio and Video Delivery

• HTML Audio and Video DOM Reference

Page 10: JavaScript APIs and Libraries

Slide 10

Basic Video Example (adapted from w3schools HTML Video)

<div id="video-container"> <video id="video1" controls> <source src="big-buck-bunny.mp4" type="video/mp4"> Your browser does not support HTML5 video. </video> <p>Video courtesy of <a href="http://www.bigbuckbunny.org/">Big Buck Bunny</a>.</p></div>

video-big-buck-bunny-basic.html

Page 11: JavaScript APIs and Libraries

Slide 11

Video with Custom User

Interface Controls

<div id="video-container"> <video id="video1"> <source src="big-buck-bunny.mp4" type="video/mp4"> Your browser does not support HTML5 video. </video> <p>Video courtesy of <a href="http://www.bigbuckbunny.org/">Big Buck Bunny</a>.</p></div>

<div id="controls"> <i id="playpause" class="far fa-play-circle fa-2x"></i> <i id="stop" class="far fa-stop-circle fa-2x"></i></div>

HTML

video-big-buck-bunny-custom-ui.html

Page 12: JavaScript APIs and Libraries

Slide 12

Video with Custom User Interface

Controls for Play/Pause, Stop

var myVideo = document.querySelector("#video1");

var playPauseButton = document.querySelector("#playpause");playPauseButton.addEventListener('click', playPause);

var stopButton = document.querySelector("#stop");stopButton.addEventListener('click', stop);

function playPause() { if (myVideo.paused) { myVideo.play(); playPauseButton.className = "far fa-pause-circle fa-2x"; } else { myVideo.pause(); playPauseButton.className = "far fa-play-circle fa-2x"; }}function stop() { myVideo.pause(); myVideo.currentTime = 0; playPauseButton.className = "far fa-play-circle fa-2x";}

JavaScript

video-big-buck-bunny-custom-ui.html

Page 13: JavaScript APIs and Libraries

Slide 13

Video on the Web Benefits of video content• Visually engaging, increases conversion rates, …

• What is video used for?

State of the Web: Video Playback Metrics• Study based on 5M websites from HTTP Archive (August 2019)

• Median mobile web page weight: 1.7MB

• Median video size: 3.8MB; 19% of videos > 10MB

• Problems: slow startup times and stalling.

How to fix? Reduce the video size• Reduce the dimensions, lower the quality, change the encoding

Some guidelines• Of videos that successfully played in 200s, the median video is 3.8 MB,

and 20s long. The most common aspect ratio is 16:9, with 720p and 1080p video dimensions dominating.

Page 14: JavaScript APIs and Libraries

Slide 14

Part 1: Overview

Part 2: Video

Part 3: Audio

Part 4: Maps

Part 5: Charts

Part 6: W3.CSS and Slideshows

Page 15: JavaScript APIs and Libraries

Slide 15

Audio on the Web Smashing: Web Design Done Well: Making Use Of Audio • Sound takes many forms: radio, music players, interviews, narration

Examples

• Narration: The New Yorker's Audio Articles – Much of their writing is read by the authors themselves

NiemanReports: Audio Articles are Helping News Outlets Gain Loyal Audiences

• Radio: Listen to the world's radio stations at Radio Garden

• Audio tours

Explore the virtual garden of a legendary Polish composer

DataArt IT museum

• Interviews: Oral Histories of World War II

• Music players: SoundCloud’s Sticky Music Player Bar

Page 16: JavaScript APIs and Libraries

Slide 16

Audio and UXThe UX of Sound: Designing Audio Experiences• Sound can be a useful tool when used appropriately: feedback,

notifications, branding, personalization, accessible interfaces

• Two considerations: only use sound when it helps, and choose the right type of audio

How sound design is transforming UX • How sound can improve online experiences

• What types of sound are there?

• The psychology of sound

• How can sound affect emotions?

• What are the challenges of sound?

• What are the major audio file formats?

• Where can I find sounds for my projects?

George Lucas: “Sound is half the experience in seeing a film”

Page 17: JavaScript APIs and Libraries

Slide 17

HTML Audio ExampleStar Wars Theme by John Williams is available from the Internet Archive and there are several data formats.

Basic player, using video controls

audio-star-wars-theme-basic.html

Or, create your own audio player to customize the controls, maintain consistency with your website color scheme, and across browsers

Firefox

Chrome

audio-star-wars-theme-custom-ui.html

Page 18: JavaScript APIs and Libraries

Slide 18

HTML AudioExample

<audio id="audio1"> <source src="https://ia902807.us.archive.org/....mp3" type="audio/mpeg"></audio>

<p>Star Wars Main Theme by John Williams</p><div id="progress"> <div id="bar"></div></div><div id="controls"> <span id="playpause" class="far fa-play-circle fa-2x"></span> <span id="stop" class="far fa-stop-circle fa-2x"></span> <span id="mute" class="fas fa-volume-up fa-2x"></span> <span id="volume-up"> <i class="fas fa-volume-up fa-1x"></i> <i class="fas fa-plus fa-1x"></i> </span> <span id="volume-down"> <i class="fas fa-volume-up fa-1x"></i> <i class="fas fa-minus fa-1x"></i> </span></div>

audio-star-wars-theme-custom-ui.html

Page 19: JavaScript APIs and Libraries

Slide 19

Some Sources for Audio/Video Content

video-corn-flakes.html

Internet Archive: Video and Audio

Library of Congress: Video and Audio

Post: ToastiesCorn Flakes, 1960susing a Classic TV Commercial from Internet Archive

Page 20: JavaScript APIs and Libraries

Slide 20

Part 1: Overview

Part 2: Video

Part 3: Audio

Part 4: Maps

Part 5: Charts

Part 6: W3.CSS and Slideshows

Page 21: JavaScript APIs and Libraries

Slide 21

Google Maps JavaScript API: Getting Started...but, you “need a project with a billing account...”

Google Maps JavaScript APITutorial: Adding a Google Map to your website

Basic

Customized

Page 22: JavaScript APIs and Libraries

Slide 22

Leaflet Map JavaScript Library

Basic Leaflet Map for San Francisco

leaflet-map.html

Leaflet Quick Start Guide• Include Leaflet CSS

• Include Leaflet JavaScript

• Add a map container, e.g., <div> element

• Initialize map with geographical coordinates

• Add a tile layer

Page 24: JavaScript APIs and Libraries

Slide 24

Using MapsMany ways...• Events: fundraisers, classes, studio tours – where?

• Selling a product: where do ingredients/materials come from, where sold?

• Narrative: personal travels, news, short stories, etc.

Some local business examples• YMCA of the Triangle – Locations

• Ronald McDonald House – Contact us

• DPAC – Getting here

Some inspiration...• 10 Creative Ways to Use (Google) Maps

• Interactive Maps on Websites

• Interactive Maps and Street View Experiences in Web Design

• Interactive Maps in Web Design

Page 25: JavaScript APIs and Libraries

Slide 25

Part 1: Overview

Part 2: Video

Part 3: Audio

Part 4: Maps

Part 5: Charts

Part 6: W3.CSS and Slideshows

Page 26: JavaScript APIs and Libraries

Slide 26

Data Visualization with ChartsGoogle Analytics example

Many chart libraries

• Datavisualization.ch Selected Tools

• Data Visualisation Catalogue

Data Visualization Resources and Tutorials

Data Visualization: Chart Dos and Don'ts

Design inspiration: information is beautiful

Page 27: JavaScript APIs and Libraries

Slide 27

Data Visualization with Chart.js

• Easy way to visualize data on your website

• Many types of charts: Samples

• How it works Add Chart.js library to your web page using <script>

Define an area in your HTML to draw the chart using a <canvas> element

Prepare your data

Draw the chart

Page 29: JavaScript APIs and Libraries

Slide 29

Basic Pie Chart <head> <title>Bar Chart - World Population</title> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> </script> </head>

<body> <canvas id="pie-chart" width="800" height="450"></canvas> <script> new Chart(document.querySelector("#pie-chart"), { type: 'pie', data: { labels: ["Africa", "Asia", "Europe", "Latin America", "North America"], datasets: [{ label: "Population (millions)", backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"], data: [2478,5267,734,784,433] }] }, options: { plugins: { title: { display: true, text: 'Predicted world population (millions) in 2050' } } } }); </script>

Chart.jsJavaScript libraries

Where the chart is drawn

pie-chart.html

Customization options

Create the chart

Page 32: JavaScript APIs and Libraries

Slide 32

Part 1: Overview

Part 2: Video

Part 3: Audio

Part 4: Maps

Part 5: Charts

Part 6: W3.CSS and Slideshows

Page 33: JavaScript APIs and Libraries

Slide 33

W3.CSS is a CSS framework• Smaller and faster than other CSS frameworks.

• Easier to learn and use than other CSS frameworks.

• Better cross-browser compatibility

• Uses standard CSS only (no jQuery or JavaScript library).

• Supports modern responsive mobile first design by default.

• Speeds up and simplifies web development

• And it's free!

Many Demos and Examples

W3.CSS Framework

Page 34: JavaScript APIs and Libraries

Slide 34

How to use• Add a link to the W3.CSS style sheet on your web page <link rel="stylesheet"

href="https://www.w3schools.com/w3css/4/w3.css">

• Or, download w3.css from w3css_downloads and add a link to w3.css on your web page

<link rel="stylesheet" href="w3.css">

W3.CSS Reference• Description of all the classes for Containers, Tables, Cards, Layout,

Navigation, Button, Input, Modal, Animation, Fonts, Text, …

• Note that many of these classes are just pre-defined style rules that you already know how to define in CSS.

W3.CSS Framework

Page 35: JavaScript APIs and Libraries

Slide 35

Automatic Slideshow Example• Several images are defined for the

slide show collection

• JavaScript displays the next image in the collection every 2 seconds

W3.CSS Slideshow

slide-show-automatic.html

var myIndex = 0;carousel();

function carousel() { var i; var x = document.querySelectorAll(".mySlides"); for (i = 0; i < x.length; i++) { x[i].style.display = "none"; } myIndex = myIndex + 1; if (myIndex > x.length) { myIndex = 1; } x[myIndex-1].style.display = "block";

setTimeout(carousel, 2000); // Change image every 2 seconds}

Create a collection of the images.

Loop through all of the images and set their display to 'none'.

Display the first image by setting the display to 'block'.

Call the system timer every 2 seconds and display the next image.

Page 36: JavaScript APIs and Libraries

Slide 36

Manual Slideshow Example• A slide index keeps track of which slide to

display

• The buttons increment/decrement the slide index to display the previous/next image.

W3.CSS Slideshow

var slideIndex = 1;showDivs(slideIndex);

function plusDivs(n) { showDivs(slideIndex += n); }

function showDivs(n) { var i; var x = document.querySelectorAll(".mySlides");

if (n > x.length) {slideIndex = 1} if (n < 1) {slideIndex = x.length} for (i = 0; i < x.length; i++) { x[i].style.display = "none"; }

x[slideIndex-1].style.display = "block";}

Create a collection of the images.

The plusDivs function increments or decrements the slide index based on which button was clicked.

The showDivs function ensures that the slide index is within the range of the number of images

Loop through all of the images and set their display to 'none'.

Set the display to 'block' for the image corresponding to the slide index.

slide-show-manual.html

Page 37: JavaScript APIs and Libraries

Slide 37

Slideshow with Image Indicator• Thumbnail images are used to show

the available images and for selection.

• Click events are associated with the thumbnail images

W3.CSS Slideshow

slide-show-image-indicator.html