ITI 134 HTML 5 Desktop and Mobile Level
ITI 134: HTML 5 Desktop and Mobile Level II Session 5 Chapter 16 - Advanced HTML 5 and CSS 3 Features Exercise 1 – Embed Fonts www. profburnett. com
Class Outline § § § Exercise 1 - Embed Fonts Exercise 2 - HTML 5 Geolocation Exercise 3 - HTML 5 Web Storage Exercise 4 - HTML 5 Canvas Exercise 5 - HTML 5 Drop and Drag 1/16/2022 Copyright © Carl M. Burnett 2
Exercise 1 - Embed Fonts 1/16/2022 Copyright © Carl M. Burnett 3
Heading with Font Imported with CSS 3 The CSS for embedding a font @font-face { font-family: Murach; src: url("HARNGTON. TTF"); } The CSS for applying the font to an HTML element #booktitle { font-family: Murach, sans-serif; } The HTML for the element that the font is applied to <h 1 id="booktitle">Murach Books</h 1> 1/16/2022 Copyright © Carl M. Burnett 4
Where to Find the Fonts § On a Windows system - C: WindowsFonts § On a Mac OS system - SystemLibraryFonts 1/16/2022 Copyright © Carl M. Burnett 5
How to Import and Apply a Font § § § Copy font family into a folder for your web site. In CSS page code rule set for the @font-face selector. Use font-family property for name. Use src Property to locate the font file. In HTML element use name as value for font-family property. List one or more other font-families in case the browser doesn’t support the CSS 3 @font-face selector. 1/16/2022 Copyright © Carl M. Burnett 6
Fonts § Free Service § 263 Font Families § https: //www. google. com/fonts 1/16/2022 Copyright © Carl M. Burnett 7
Heading that uses Google Web Font The CSS for importing a Google Web Font <link href="http: //fonts. googleapis. com/css? family=Sorts+Mill+Goudy" rel="stylesheet"> The CSS for applying the font to an HTML element #booktitle { font-family: "Sorts Mill Goudy", serif; } The HTML for the element the font is applied to <h 1 id="booktitle">Murach Books</h 1> 1/16/2022 Copyright © Carl M. Burnett 8
Adobe Typekit Editor § Free account limited to two fonts § https: //typekit. com/ 1/16/2022 Copyright © Carl M. Burnett 9
How to apply a Typekit font to an element Code the class attribute with its value set to the name that was displayed in the upper-left corner of the Typekit Editor. The script elements for importing Typekit fonts <script src="http: //use. typekit. com/vxu 5 ibx. js"></script> <script>try{Typekit. load(); }catch(e){}</script> The HTML for an element that a font is applied to <h 1 class="tk-blambot-pro">Murach Books</h 1> 1/16/2022 Copyright © Carl M. Burnett 10
Exercise 2 – HTML 5 Geolocation Next 1/16/2022 Copyright © Carl M. Burnett 11
Exercise 2 - HTML 5 Geolocation 1/16/2022 Copyright © Carl M. Burnett 12
Outline § § Location Techniques Detecting the Location Maps/Navigation App Integration Showing a Map 1/16/2022 Copyright © Carl M. Burnett 13
Location Techniques § Server Techniques § Accuracy § Indoor Location § Client Techniques § § 1/16/2022 GPS A-GPS Cell information Wi. Fi Positioning System § § IETF DHCP Coordinate LCI IP address Conversion Carrier connection Language § Asking the User Copyright © Carl M. Burnett 14
Detecting the Location The W 3 C Geolocation API - Getting the position navigator. geolocation. get. Current. Position(user. Located, location. Error); function user. Located(position) { var latitude = position. coords. latitude; var longitude = position. coords. longitude; var time. Of. Location = position. timestamp; } function location. Error(error) { alert(error. code); } 1/16/2022 Copyright © Carl M. Burnett 15
W 3 C Geolocation API Properties Property Description latitude in decimal degrees longitude in decimal degrees accuracy in meters altitude (optional) in meters above the ellipsoid altitude. Accuracy (optional) in meters heading (optional) in degrees clockwise related to true north speed (optional) in meters per second 1/16/2022 Copyright © Carl M. Burnett 16
Getting a Geolocation HTML for Geolocation <input type="button" value="Get Location“ on. Click=“get. Location()"> Javascript for Geolocation <script> var x = document. get. Element. By. Id("demo"); function get. Location() { if (navigator. geolocation) { navigator. geolocation. get. Current. Position(show. Position); } else { x. inner. HTML = "Geolocation is not supported by this browser. "; } } function show. Position(position) { x. inner. HTML="Latitude: " + position. coords. latitude + " Longitude: " + position. coords. longitude; } </script> 1/16/2022 Copyright © Carl M. Burnett In Firefox Example W 3 C Exercise 17
Showing a Map j. Query The HTML that starts the Java. Script and receives the map <body on. Load="init. Geolocation()"> <p>Your current location is: </p> <img src="" id="map"> </body> 1/16/2022 The Java. Script that gets the map and uses j. Query to place it function init. Geolocation() { navigator. geolocation. get. Current. Positio n(get. Location); } function get. Location(position) { var url = "http: //maps. google. com/maps/api/static map? sensor=false¢er=" + position. coords. latitude + ", " + position. coords. longitude + "&zoom=14&size=300 x 400&markers=color: re d|" + position. coords. latitude + ", " + position. coords. longitude; $("#map"). attr("src", url); } Copyright © Carl M. Burnett 18
Showing a Map Google API function show. Position(position) { var latlon = position. coords. latitude+", "+position. coords. longitude; var img_url = "http: //maps. googleapis. com/maps/api/staticmap? center=" +latlon+"&zoom=14&size=400 x 300&sensor=false"; document. get. Element. By. Id("mapholder"). inner. HTML = "<img src='"+img_url+"'>"; } In Firefox Example W 3 C Exercise 1/16/2022 Copyright © Carl M. Burnett 19
Handling Error Messages Error constant Description PERMISSION_DENIED The user has denied permission to the API to get the position. POSITION_UNAVAILABLE The user’s position couldn’t be determined due to location provider. TIMEOUT The user’s position couldn’t be determined before the timeout function init. Geolocation() { navigator. geolocation. get. Current. Position( get. Location, error. Handling); } In Firefox W 3 C Exercise 1/16/2022 function init. Geolocation() { navigator. geolocation. get. Current. Position( get. Location, error. Handling); } function error. Handling(error) { switch(error. code) { case error. PERMISSION_DENIED: alert( "Not sharing your location. "); break; case error. POSITION_UNAVAILABLE: alert( "Cannot detect position. "); break; case error. TIMEOUT: alert( "Position retrieval timed out. "); break; default: alert("Unknown error. "); break; } } Copyright © Carl M. Burnett 20
Tracking the location // Global variable to store the watch ID var watch. Id = false; // This function may be called by an HTML element function tracking. Button. Click() { if (watch. Id==false) { // Tracking is off, turn it on var watch. Id = navigator. geolocation. watch. Position(user. Located, location. Error); } else { // Tracking is on, turn it off navigator. geolocation. clear. Watch(watch. Id); watch. Id = false; } } 1/16/2022 Copyright © Carl M. Burnett 21
Defining Optional Attributes Property Type Default value enable. High. Accuracy Boolean false timeout Long (in milliseconds) Infinity maximum. Age Long (in milliseconds) 0 navigator. geolocation. get. Current. Position(user. Located, location. Error, {timeout: 10000, maximum. Age: 30000, enable. High. Accuracy: false}); 1/16/2022 Copyright © Carl M. Burnett 22
Detecting the Location § § § Carrier Network Geolocation APIs GSMA One. API IETF DHCP Coordinate LCI IP Geolocation Conversion Google’s Client. Location object 1/16/2022 Copyright © Carl M. Burnett 23
Carrier Geolocation API Availability Platform Carriers URL Verizon Network API Verizon (US) developer. verizon. com Blue. Via Movistar (Latin America, Spain), O 2 (UK, Germany), Telenor (Asia, Scandinavia, Eastern Europe) bluevia. com AT&T Location API AT&T (US) developer. att. com/developer LBS Sprint API Sprint (US) developer. sprint. com 1/16/2022 Copyright © Carl M. Burnett 24
GSMA One. API https: //developer. aepona. com/Terminal. Location. Service/Proxy/REST/<key>? address=tel: <tel>&accuracy=coarse Where: <key> = the key assigned to our developer account <tel> = the international number of the phone we want to geolocate. <response timestamp="2010 -06 -06 T 12: 31: 07. 014 Z" longitude="10. 22244" latitude="54. 601505" altitude="10. 0" accuracy="200"/> 1/16/2022 Copyright © Carl M. Burnett 25
IETF DHCP Coordinate LCI Internet Engineering Task Force (IETF) Dynamic Host Control Protocol (DHCP) Option for Coordinate Location Configuration Information (C-LCI) Protocol § § § Specifies Dynamic Host Configuration Protocol options (DHCPv 4 and DHCPv 6) For Coordinate-based Geographic Location of a client. Location Configuration Information (LCI) includes: § § § 1/16/2022 Latitude Longitude Altitude Resolution or Uncertainty Separate parameters for Geographic Datum Copyright © Carl M. Burnett 26
IP Geolocation Conversion § Once we have the IP address § Use a web service to get the country/city details, § Max. Mind's Geo. IP - Enable identification of: § § 1/16/2022 Location (Geographic Coordinates) Organization Connection speed User type Copyright © Carl M. Burnett 27
Google’s Client. Location Object <script src="https: //www. google. com/jsapi"></script> To use the client location feature, we must then load an API. For example: <script type="text/javascript"> google. load("search", "1"); </script> Once we’ve loaded the API, the google. loader. Client. Location object will be populated with properties like the following: • • • latitude longitude address. city address. country_code address. region 1/16/2022 Copyright © Carl M. Burnett 28
Maps/Navigation App Integration § Google Maps for Android § i. OS Maps § Bing Maps 1/16/2022 Copyright © Carl M. Burnett 29
Google Maps for Android § http: //maps. google. com/? <attributes>. § Possible attributes include: § q - Query parameter; this can be a comma-separated coordinate preceded by a loc: prefix (loc: lat, long), or any search string, such as starbucks § near - Applies a location definition for a query, as in q=starbucks; near=san+mateo+ca § ll - A comma-separated latitude and longitude for the map center § t - The type of map (m: map, k: satellite, h: hybrid, p: terrain) § z - The zoom level, from 1 (the whole world) to 23 (buildings, not available in all areas) 1/16/2022 Copyright © Carl M. Burnett 30
Google Maps – Street View § google. streetview: protocol. § The parameters are: § cbll - The latitude and longitude, comma-separated (mandatory) § cbp - A series of optional parameters, such as yaw (center of panorama view in degrees clockwise from north), pitch (center of panorama view in degrees from − 90 to 90), and the panorama zoom § mz - The map zoom associated with this panorama 1/16/2022 Copyright © Carl M. Burnett 31
i. OS Maps <a href="http: //maps. google. com/? q=eiffel+tower+paris"> See the Eiffel Tower on a map </a> We now need to use: <a href="http: //maps. apple. com/? q=eiffel+tower+paris"> See the Eiffel Tower on a map </a> 1/16/2022 Copyright © Carl M. Burnett 32
Bing Map APIs Bing Maps API bingmaps: protocol, which accepts the following parameters (a partial list): § § § § cp - The center point—a latitude and longitude, separated by a tilde ~ character lvl - The zoom level (1– 20) where - A search query on places, locations, or landmarks q - A search query on a local business sty - The map style (a: aerial, r: roadmap) trfc - Whether or not traffic information should be included (0: no, 1: yes) rtp - The route definition, with the source and destination addresses separated by a tilde ~ character; if either the source or the destination is undefined it will make a route from/to the current location 1/16/2022 Copyright © Carl M. Burnett 33
Showing a Map <html> <head> <meta name="viewport" content="initial-scale=1. 0, user-scalable=no" /> <script type="text/javascript" src="http: //maps. google. com/maps/api/js? sensor=true"></script> <script type="text/javascript"> function init() { var useragent = navigator. user. Agent; var div. Map = document. get. Element. By. Id("map"); if (useragent. index. Of('i. Phone') != − 1 || useragent. index. Of('Android') != − 1 || useragent. index. Of('i. Pod') != − 1 ) { div. Map. style. width = '100%'; div. Map. style. height = '100%'; position = get. Position(); // This needs to be implemented var latlng = new google. maps. Lat. Lng(position. latitude, position. longitude); var options = { zoom: 7, center: latlng, map. Type. Id: google. maps. Map. Type. Id. ROADMAP }; var map = new google. maps. Map(document. get. Element. By. Id("div. Map"), options); } else { // Google Maps not compatible with this mobile device } } </script> </head> <body onload="init()"> <div id="div. Map"></div> </body> </html> 1/16/2022 Copyright © Carl M. Burnett 34
Exercise 3 - HTML 5 Web Storage Next 1/16/2022 Copyright © Carl M. Burnett 35
Exercise 3 - HTML 5 Web Storage 1/16/2022 Copyright © Carl M. Burnett 36
Outline § § Web Storage Web SQL Database API Indexed. DB API File. System API 1/16/2022 Copyright © Carl M. Burnett 37
Web Storage § § § HTML 5 Web Storage API defines two stores local. Storage and session. Storage Scopes are different Local store is used for long-term storage Session store doesn’t persist after closing tab or window 1/16/2022 Copyright © Carl M. Burnett 38
Web Storage Limits Browser/platform Initial local storage limit Session storage limit Limit can be exceeded Safari on i. OS 2. 5 MB UTF-16 No Android browser 2. 5 MB UTF-16 No limit No Chrome for Android 2. 5 MB UTF-16 No Nokia Browser for Symbian 2. 5 MB UTF-16 No Nokia Browser for Mee. Go 2. 5 MB UTF-16 No limit No Black. Berry browser for smartphones 2. 5 MB UTF-16 No limit No Black. Berry browser for Play. Book and BB 10 12 MB No Internet Explorer 5 MB No Opera Mobile 1 MB Shared with local Yes, with permission Firefox 2 MB No limits No 1/16/2022 Copyright © Carl M. Burnett 39
The Syntax for Storage The Syntax for Local Storage local. Storage. set. Item("itemname", "value") local. Storage. get. Item("itemname") local. Storage. remove. Item("itemname") local. Storage. clear() // saves the data in the item // gets the data in the item // removes all items The Syntax for Session Storage session. Storage. set. Item("itemname" "value") session. Storage. get. Item("itemname") session. Storage. remove. Item("itemname") session. Storage. clear() 1/16/2022 Copyright © Carl M. Burnett // saves the data in the item // gets the data in the item // removes all items 40
Web Storage Examples local. Storage. set. Item("name_in_the_storage", object_to_store); local. Storage. get. Item("name_in_the_storage"); local. Storage. itemname session. Storage. itemname // Save an object or variable in the store // Read an object from the store var object = // Saves or gets the data in the local storage item // Saves or gets the data in the session storage item Java. Script that uses local storage for a hit counter <p>You have visited this page <output> <script> if (local. Storage. hits) { local. Storage. hits = Number(local. Storage. hits) + 1; } else { local. Storage. hits = 1; } document. write(local. Storage. hits); </script> </output> time(s). </p> 1/16/2022 Copyright © Carl M. Burnett Example 41
Web SQL Database API Outline § § § § Overview Creating the database and its tables Adding values to a table Building the manage page Description and Options Validation Inserting Date into the database 1/16/2022 Copyright © Carl M. Burnett 42
Web SQL Database API § § § Web SQL DB implements using the open source SQLite. Abandoned by W 3 C Web SQL Database used in: § § § § Safari Chrome Android Black. Berry Opera Mobile Not used in Mozilla and Microsoft Apache Cordova/Phone. Gap supports it in Windows Phone native web app emulating the SQL Server engine. 1/16/2022 Copyright © Carl M. Burnett 43
Creating the database and its tables <script type=”text/javascript” language=”Javascript”> var db; $(document). ready(function(){ }); </script> <script var }); $(document). ready(function(){ db; type=”text/javascript” language=”Javascript”> var db = </script> window. open. Database(internal. Name, version, display. Name, size. Expectable, [callback]); var db; $(document). ready(function(){ db = open. Database(‘my. Music’, ‘ 1. 0’, ‘My Music Database’, 2 * 1024); }); 1/16/2022 Copyright © Carl M. Burnett 44
Web SQL HTML 5 Database Creation Variables Variable Name Required Description Database. Name Yes This is the standard database name that you want your application to use. This is important because you reference this when you start building queries. Database. Version Yes This is the version number of your current database in string format, such as 1. 0. HTML 5 databases enable you to have multiple versions of a database on a local device. For our demo, you use 1. 0. Display. Name No This is the database description in string format. It isn’t a required field, but it can be useful if you have lots of local databases and need to remember which database stores which information. Estimated. Size Yes This is one of the most important pieces of information for initializing the database. This value sets the size of the database using the following byte format: 50 * 1024. The max size for a database without prompting the user is 5 MB. In this example, that is 100 MB. Call. Back No This is a function that is called when the database has been completed. Normally, you would put all your CREATE TABLE syntax in this function so once the table is opened, you start to create the tables. 1/16/2022 Copyright © Carl M. Burnett 45
Building the Tables in “My. Music” DB db. transaction(function (t) { t. execute. Sql(“CREATE TABLE IF NOT EXISTS songs (song_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, song_name, song_album, company_id, genre_id, song_writer, song_artists, created_at)”, null, s. R, f. R); t. execute. Sql(“CREATE TABLE IF NOT EXISTS company (company_id INTEGER PRIMARY KEY AUTOINCREMENT, company_name, company_address, company_state, company_zip, company_phone, created_at)”, null, s. R, f. R); t. execute. Sql(‘CREATE TABLE IF NOT EXISTS genre (genre_id PRIMARY KEY AUTOINCREMENT, genre_name, created_at)’, null, s. R, f. R); t. execute. Sql(‘CREATE TABLE IF NOT EXISTS concerts (concerts_id PRIMARY KEY AUTOINCREMENT, song_id, concert_name, concert_date, concert_city, created_at)’, null, s. R, f. R); }); 1/16/2022 Copyright © Carl M. Burnett 46
s. R and f. R callback s. R = success. Response - This function is called when the SQL statement has executed successfully. The function enables two variables, which represent the transaction (first variable) and the result set (second variable). This does not apply for inserts, updates, deletions, or create tables. f. R = error. Response - This function is called when the SQL statement fails. The function takes two variables, which represent the transaction (first variable) and the error (second variable). function s. R(a, b){ // The query was successfully! } function f. R(a, b){ // Oops! There was an issue. Let’s alert the user. alert(b. message); } 1/16/2022 Copyright © Carl M. Burnett 47
Adding values to a song table db. transaction(function (t) { t. execute. Sql(“SELECT * from songs where songs_name = ? ”, [‘The Light’], function(tx, res) { if (res. rows. length == 0) { var start = new Date(). get. Time(); t. execute. Sql(“INSERT INTO songs (song_name, song_album, company_id, genre_id, song_writer song_artists, created_at) VALUES(‘The Light’, ‘Kaleidoscope Heart’, ‘Epic’, ‘Pop’, ‘Sara Bareilles’, ‘September 7, 2010’)”, [start], null, f. R); t. execute. Sql(“INSERT INTO songs (song_name, song_album, company_id, genre_id, song_writer song_artists, created_at) VALUES(‘Breathe Again’, ‘Kaleidoscope Heart’, ‘Epic’, ‘Pop’, ‘Sara Bareilles’, ‘September 7, 2010’)”, [start], null, f. R); t. execute. Sql(“INSERT INTO songs (song_name, song_album, company_id, genre_id, song_writer song_artists, created_at) VALUES(‘Gravity’, ‘Little Voice’, ‘Epic’, ‘Pop’, ‘Sara Bareilles’, ‘July 3, 2007’)”, [start], null, f. R); } else { // the table already has values - so let’s leave it alone. } }, f. R); ); 1/16/2022 Copyright © Carl M. Burnett 48
Building the manage page <h 2>Add A Song</h 2> <form id=”manage-form” data-ajax=”false” onsubmit=”handle. Form(); return false; ”> </form> $(“#manage-form”). submit(function() { Return false; }) <label <input <label <input for=”song_name”>Song Name: </label> type=”text” name=” song_name” id=” song_name” data-mini=”true” /> for=”song_album”>Album Name: </label> type=”text” name=” song_album” id=” song_album” data-mini=”true” /> for=”company_id”>Company Name: </label> type=”text” name=”company_id” id=”company_id” data-mini=”true” /> for=”genre_id”>Genre: </label> type=”text” name=”genre_id” id=”genre_id” data-mini=”true” /> for=”song_writer”>Song Writers Name: </label> type=”text” name=”song_writer” id=” song_writer” data-mini=”true” /> for=”song_artists”>Artists: </label> type=”text” name=”song_artists” id=”song_artists” data-mini=”true” /> 1/16/2022 Copyright © Carl M. Burnett 49
Drop-down list to show all the Genres <label for=”genre_id” class=”select”>genre: </label> <select name=”genre_name” id=”genre_id” data-mini=”true”></select> get_genre: function get_genre () { db. transaction(function (t) { t. execute. Sql(“SELECT * from genre order by genre_name”, null, function(t, res) { if (res. rows. length == 0) { // this shouldn’t happen - as we already inserted them. } else <select name=”wine_color” id=”color_id” data-mini=”true”></select> { var len = res. rows. length; var code = “”; for (var i = 0; i < len; i++) { code = code + ‘<option value=”’+res. rows. item(i). genre_id+’”>’+res. rows. item(i). genre_name+’</option>’; } $(“#genre_id”). html(code); } }, f. R); } 1/16/2022 Copyright © Carl M. Burnett 50
Concerts, Options, and Submit <label for=”concert” class=”select”>Concert: </label> <select name=”concert_name” id=”concert_id” data-mini=”true”></select> <label for=”is_add”>Do you want to add this s ong to a concert? </label> <input type=”checkbox” name=”is_add” onchange=”toggle. Box(this); ” id=”is_add” class=”custom” /> <div id=”concert_ques” style=”display: none; ”> <label for=”concert_city”>Concert City: </ label> <input type=”text” name=”concert_city” id=”concert_city” value=”” /> <label for=”concert_name”>Concert Name: </ label> <input type=”text” name=”concert_name” id=” concert_name” value=”” /> <label for=”concert_date”>Concert Date: </label> <input type=”date” name=” concert_date” id=” concert_date” value=”” /> </div> <input type=”submit” value=”Add Wine” /> 1/16/2022 Copyright © Carl M. Burnett 51
Function that will support showing or hiding the div function toggle. Box(a) { if ($(a). is(‘: checked’)) { $(“#concert_ques”). show(); $(“#concert_ques input”). add. Class(“required”); } else $(“#cellar_ques function }{$eif (“#cellar_ques”). show(); lse (“#cellar_ques”). hide(); ($(a). is(‘: checked’)) toggle. Box(a) input”). add. Class(“required”); input”). remove. Class(“required”); { } { $(“#concert_ques”). hide(); $(“#concert_ques input”). remove. Class(“required”); } } 1/16/2022 Copyright © Carl M. Burnett 52
Validation Create a new class in all elements called required <label for=”song_name” class=“select”>Song Name: </label> <select class=”required” input type=”text” name=” song_name” id=” song_name” data-mini=”true ”> </select> <label for=”song_album” class=“select”>Album Name: </label> <input type=”text” name=” song_album” id=” song_album” data-mini=”true ”/> <label for=”company_id” class=“select”>Company Name: </label> <input type=”text” name=”company_id” id=”company_id” data-mini=”true ”/> <label for=”genre_id” class=“select”>Genre: </label> <input type=”text” name=”genre_id” id=”genre_id” data-mini=”true ”></select> < select class=”required” label for=”song_writer” class=“select”>Song Writers Name: </label> <input type=”text” name=”song_writer” id=” song_writer” data-mini=”true ”/> <label for=”song_artists ” class=“select”>Artists: </label> < select class=”required” input type=”text” name=”song_artists” id=”song_artists” datamini=”true”></select> 1/16/2022 Copyright © Carl M. Burnett 53
Validation Create a Java. Script function of handle. Form HTML form <h 2>Add A Song</h 2> <div class=”success” id=”success-msg” style=”display: none; ”> Awesome, your song is created! </div> <div class=”error” id=”error-msg” style=”display: none; ”> You have errors in your form, please check the data. </div> <form id=”manage-form” data-ajax=”false” onsubmit=”handle. Form(); return false; ”> … </form> CSS to change the text to be read at the top of the HTML style sheet: <style type=”text/css” media=”screen”> label. error { color: #FF 0000; font-weight: bold; } </style> 1/16/2022 function handle. Form() { var is_error = false; $(“#error-msg”). hide(); $(“#manage-form input”). each(function() { $(this). prev(). remove. Class(“error”); }); $(“. required”). each(function() { if ($(this). val() == “”) { $(this). prev(). add. Class(“error”); is_error = true; } }); if (is_error) { $(“#error-msg”). show(); } else { …. } } Copyright © Carl M. Burnett 54
Validation Create a Java. Script function of handle. Form function handle. Form() { var is_error = false; $(“#error-msg”). hide(); $(“#manage-form input”). each(function() { $(this). prev(). remove. Class(“error”); }); $(“. required”). each(function() { if ($(this). val() == “”) { $(this). prev(). add. Class(“error”); is_error = true; } }); if (is_error) { $(“#error-msg”). show(); } else { 1/16/2022 var wine_name = $(“#wine_name”). val(); var winery_name = $(“#winery_name”). val(); var color_id= $(“#wine_color”). val(); var wine_abv = $(“#wine_abv”). val(); var wine_description = $(“#wine_description”). val(); var qty = $(“#cellar_qty”). val(); var note = $(“#cellar_description”). val(); add. Wine. Activity(wine_name , winery_id, wine_abv, color_id, $(“#is_add”). is(‘: checked’), wine_description, qty, note); } return false; Copyright © Carl M. Burnett 55
Inserting Data into the database db. transaction(function (tx) { tx. execute. Sql(“INSERT Into test_table (test_var) values(? )”, [‘test’], function(tx, res) { // you can get the ID of the insert if you are using auto-increment fields by using res. insert. Id var new_id= res. insert. Id }, f. R); }); 1/16/2022 Copyright © Carl M. Burnett 56
Inserting Data into the database function add. Wine. Activity(wine_name, winery_name, wine_abv, color_id, is_act, wine_description, qty, note) { db. transaction(function (tx) { tx. execute. Sql(“SELECT winery_id from winery where winery_name = ? ”, [winery_name], function(tx, res) { if (res. rows. length == 0) { var start = new Date(). get. Time(); tx. execute. Sql(“INSERT INTO winery (winery_name, created_at) VALUES(? , ? )”, [winery_name, start], function(trx, response) { var a = response. insert. Id; add. Wine(wine_name, a, wine_abv, color_id, wine_description, is_act, qty, note); } , f. R); } else { var a = res. rows. item(0). winery_id; add. Wine(wine_name, a, wine_abv, color_id, wine_description, is_act, qty, note); } }, f. R); } 1/16/2022 Copyright © Carl M. Burnett 57
Inserting Data into the database function add. Wine(wine_name, winery_id, wine_abv, color_id, wine_description, is_act, qty, note) { db. transaction(function (tx) { var start = new Date(). get. Time(); tx. execute. Sql(“INSERT into wines (wine_name, wine_description, wine_abv, winery_id, color_id, created_at) values (? , ? , ? )”, [wine_name, wine_description, wine_abv, winery_id, color_id, start], function(tx, res) { var a = res. insert. Id; if (is_act) { add. Activity(a, qty, note); } $(“#success-msg”). show(); $(“#manage-form input”). val(‘’); $(“#manage-form textarea”). val(‘’); }, f. R); } 1/16/2022 Copyright © Carl M. Burnett 58
Inserting Data into the database function add. Activity(wine_id, activity_qty, activity_note) { db. transaction(function (tx) { var start = new Date(). get. Time(); tx. execute. Sql(“INSERT into activity (wine_id, activity_quantity, activity_not, created_at) values (? , ? )”, [wine_id, activity_qty, activity_note, start], null, f. R); } 1/16/2022 Copyright © Carl M. Burnett 59
Inserting Data into the database function handle. Form() { var is_error = false; $(“#error-msg”). hide(); $(“#manage-form input”). each(function() { $(this). prev(). remove. Class(“error”); }); $(“. required”). each(function() { if ($(this). val() == “”) { $(this). prev(). add. Class(“error”); var wine_name = $(“#wine_name”). val(); is_error = true; var winery_name = $(“#winery_name”). val(); } var color_id= $(“#wine_color”). val(); }); var wine_abv = $(“#wine_abv”). val(); if (is_error) { var wine_description = $(“#wine_description”). val(); $(“#error-msg”). show(); var qty = $(“#cellar_qty”). val(); return false; var note = $(“#cellar_description”). val(); } add. Wine. Activity(wine_name, winery_id, wine_abv, color_id, else { $(“#is_add”). is(‘: checked’), wine_description, qty, note); return false; } } 1/16/2022 Copyright © Carl M. Burnett 60
Indexed. DB API § § Indexed. DB is the W 3 C standard IDB not available in: § Safari on i. OS before version 6. 0 § Android browser prior to version 4. 1 § § Implemented in Chrome, Firefox, and Internet Explorer (from version 10 Basic concepts: § § § database repository multiple object stores (similar to tables) objects (similar to records) Indexed with a key (similar to a primary key). IDB does not support SQL commands. 1/16/2022 Copyright © Carl M. Burnett 61
Indexed. DB API The main functionality happens in the global indexed. DB object: • • • window. indexed. DB window. webkit. Indexed. DB window. moz. Indexed. DB; Opening a database var db. Request = indexed. DB. open("my. Database"); var database; db. Request. onsuccess = function(event) { // The database object appears as event. result database = event. result; } db. Request. onerror = function(event) { // Manage error } 1/16/2022 Note Using Modernizr we can query about storage API support using the properties localstorage, sessionstorage, websqldatabase, indexeddb, and applicationcache. There are polyfills to backfill functionality in old browsers. Copyright © Carl M. Burnett 62
Indexed. DB API To create the object stores and schemas we implement upgradeneeded event db. Request. onupgradeneeded = function(event) { var db = event. target. result; // Let's create the object store for books var object. Store = db. create. Object. Store("books", { key. Path: "isbn" }); } To execute commands on an object store we need to use transactions var transaction = database. transaction("books", 'readwrite'); transaction. object. Store("books"). add({ isbn: "1234567890", name: "Programming the Mobile Web"}) 1/16/2022 Copyright © Carl M. Burnett 63
Indexed. DB API To get one element by key from the database. transaction("books"). object. Store("books"). get("1234567890"). onsuccess = function(event) { var object = event. target. result ; }); To browse between all objects var all. Books = database. transaction("books"). object. Store("books"); all. Books. open. Cursor(). onsuccess = function(event) { var cursor = event. target. results; if (cursor) { var key = cursor. key; var current. Book = cursor. value; cursor. continue(); // Move to next element and execute // onsuccess again } else { // End of object store } }; 1/16/2022 Copyright © Carl M. Burnett 64
File. System API § § § File. System API is a W 3 C draft specification. API can create and manage folders and files in a virtual filesystem. Some browsers may implement it using a database. Only works with the files created by scripts in our domain. Two kinds of filesystem: § PERSISTENT § TEMPORARY 1/16/2022 Copyright © Carl M. Burnett 65
File. System API To retrieve a persistent filesystem of 4 MB, we can use the following code : window. request. File. System(window. PERSISTENT, 4*1024, function(filesystem) { // The filesystem was created/opened }, function(event) { // Handle error }); 1/16/2022 Copyright © Carl M. Burnett 66
File. System API § With this API we can: § § § § Modify filesystem quotas Create and open files Append, replace, and delete files Create and delete directories Copy, rename, and move files and directories Read directories’ content Create filesystem URLs With this API we also have a new URI, filesystem: , that we can use to point from our web app to any file stored in our persistent or temporary storage. 1/16/2022 Copyright © Carl M. Burnett 67
Exercise 4 - HTML 5 Canvas Next 1/16/2022 Copyright © Carl M. Burnett 68
Exercise 4 - HTML 5 Canvas 1/16/2022 Copyright © Carl M. Burnett 69
HTML 5 Canvas 1/16/2022 Copyright © Carl M. Burnett 70
Create a Canvas Tag <canvas id="my. Canvas" width="200" height="100"></canvas> Create a Canvas HTML <!DOCTYPE html> <body> <canvas id="my. Canvas" width="200" height="100" style="border: 1 px solid #000000; "> Your browser does not support the HTML 5 canvas tag. </canvas> </body> </html> 1/16/2022 W 3 C Exercise Copyright © Carl M. Burnett 71
Draw Onto The Canvas With Java. Script <script> var c = document. get. Element. By. Id("my. Canvas"); var ctx = c. get. Context("2 d"); ctx. fill. Style = "#FF 0000"; ctx. fill. Rect(0, 0, 150, 75); </script> Canvas Coordinates • • The canvas is a two-dimensional grid. The upper-left corner of the canvas has coordinate (0, 0) So, the fill. Rect() method above had the parameters (0, 0, 150, 75). This means: Start at the upper-left corner (0, 0) and draw a 150 x 75 pixels rectangle. 1/16/2022 Copyright © Carl M. Burnett W 3 C Exercise 72
Canvas - Paths • • To draw straight lines on a canvas, we will use the following two methods: • move. To(x, y) defines the starting point of the line • line. To(x, y) defines the ending point of the line To actually draw the line, we must use one of the "ink" methods, like stroke(). Java. Script: var c = document. get. Element. By. Id("my. Canvas"); var ctx = c. get. Context("2 d"); ctx. move. To(0, 0); ctx. line. To(200, 100); ctx. stroke(); W 3 C Exercise 1/16/2022 Copyright © Carl M. Burnett 73
Canvas - Circle arc(x, y, r, start, stop) Java. Script: var c = document. get. Element. By. Id("my. Canvas"); var ctx = c. get. Context("2 d"); ctx. begin. Path(); ctx. arc(95, 50, 40, 0, 2*Math. PI); ctx. stroke(); W 3 C Exercise 1/16/2022 Copyright © Carl M. Burnett 74
Canvas - Text To draw text on a canvas, the most important property and methods are: • font - defines the font properties for text • fill. Text(text, x, y) - Draws "filled" text on the canvas • stroke. Text(text, x, y) - Draws text on the canvas (no fill) Java. Script: var c = document. get. Element. By. Id("my. Canvas"); var ctx = c. get. Context("2 d"); ctx. font = "30 px Arial"; ctx. fill. Text("Hello World", 10, 50); W 3 C Exercise 1/16/2022 Copyright © Carl M. Burnett 75
Canvas - Gradients There are two different types of gradients: • create. Linear. Gradient(x, y, x 1, y 1) • create. Radial. Gradient(x, y, r, x 1, y 1, r 1) - Creates a linear gradient - Creates a radial/circular gradient Java. Script – Linear Gradient: var c = document. get. Element. By. Id("my. Canvas"); var ctx = c. get. Context("2 d"); // Create gradient var grd = ctx. create. Linear. Gradient(0, 0, 200, 0); grd. add. Color. Stop(0, "red"); grd. add. Color. Stop(1, "white"); // Fill with gradient ctx. fill. Style = grd; ctx. fill. Rect(10, 150, 80); 1/16/2022 W 3 C Exercise Linear Gradient W 3 C Exercise Radial Gradient Copyright © Carl M. Burnett 76
Canvas - Images To draw an image on a canvas, we will use the following method: draw. Image(image, x, y) Java. Script: var c = document. get. Element. By. Id("my. Canvas"); var ctx = c. get. Context("2 d"); var img = document. get. Element. By. Id("scream"); ctx. draw. Image(img, 10); W 3 C Exercise 1/16/2022 Copyright © Carl M. Burnett 77
Exercise 5 - HTML 5 Drop and Drag Next 1/16/2022 Copyright © Carl M. Burnett 78
Exercise 5 - HTML 5 Drop and Drag 1/16/2022 Copyright © Carl M. Burnett 79
Drag and Drop Events Service Description dragstart Instantiated when drag is started drag Instantiated after dragstart has started dragenter Instantiated when the mouse is first moved over a draggable element Dragleave Instantiated when a mouse leaves an element while a drag is occurring dragover Instantiated when mouse moves over an element when drag is occurring dragend Instantiated when a dragged object has been dropped and the operation is over drop Instantiated when dragged object is dropped 1/16/2022 Copyright © Carl M. Burnett 80
Drag and Drop HTML <img src="images/book 1. jpg" draggable="true" ondragstart="drag(this, event)" <img src="images/book 2. jpg" draggable="true" ondragstart="drag(this, <img src="images/book 3. jpg" draggable="true" ondragstart="drag(this, <img src="images/book 5. jpg" draggable="true" ondragstart="drag(this, 2010"> <div id="cart" ondrop="drop(this, event)" ondragenter="return false" ondragover="return false"> <strong>Shopping Cart (Drag books here)</strong> </div> <input type="button" value="Checkout"> 1/16/2022 Copyright © Carl M. Burnett id="SQL event)" Server 2008"> id="PHP and My. SQL"> id="Visual Basic 2010"> id="ASP. NET 4 with VB 81
Drag and Drop Java. Script <script> function drag(target, e) { e. data. Transfer. set. Data('Text', target. id); } function drop(target, e) { if (e. prevent. Default) { e. prevent. Default(); } target. inner. HTML += '<p>' + e. data. Transfer. get. Data('Text') + '</p>'; } </script> Example 1/16/2022 Copyright © Carl M. Burnett 82
Student Exercise 1 § Complete Exercise 16 -1 on page 555 and 16 -2 on page 556 using Dreamweaver. § Upload your HTML pages and CSS files to the live site to preview. 1/16/2022 Copyright © Carl M. Burnett 83
Class Review § § § Embed Fonts HTML 5 Geolocation HTML 5 Web Storage HTML 5 Canvas HTML 5 Drop and Drag That’s All Folks! 1/16/2022 Copyright © Carl M. Burnett 84
- Slides: 84