Frontend Web Programming PDF
Document Details
Uploaded by PureJoy
Santa Clara University
Ming-Hwa Wang
Tags
Summary
This document is an introduction to frontend web programming, with a focus on HTML. It covers basic concepts and examples.
Full Transcript
Frontend Web Programming Broaden your Horizons with Packt Packt Lessons...
Frontend Web Programming Broaden your Horizons with Packt Packt Lessons Packt: Always finding a way Ming-Hwa Wang, Ph.D COEN 278 Advanced Web Programming Department of Computer Science and Engineering Santa Clara University Introduction to HTML HTML (HyperText Markup Language derived from Standard Generalized Markup Language SGML) access text from other document via hyperlinks using protocol HTTP tags are keyword surrounded by angular brackets and come in pairs (opening tags and closing tags): , , , formatting example , , , , , , , , , , , , , , , , , , Formatting in HTML , , , , , Strong Font , , , , , , , , , , , , , , Coding: Conditions and Loops: variables x and y exception - tags with no closing tags: (for HTML5), , , , , , , , The Packt Initiative headings are useful for search engine optimization (SEO) element attribute : id=”…”, class=”…”, style=”…”, etc. Packt: Always finding a way Life has its Ups and Downs Stay Cool The Packt Initiative #packtpub { color:navy; font-style: italic; }.learn { color: maroon; font-size: 40px; } Welcome to Packt Links Links in HTML A normal link Packt Library Image acts like a hyperlink An email link image example Send Email Go to the Heading tag Images in HTML Image in an HTML doc block and inline elements example Block and inline elements link example Paragraph and Div Big Data is the hottest trend in the IT industry at the moment. Companies are realizing the value of collecting, retaining, and analyzing as much data as possible. They are therefore rushing to implement the next generation of data platform, and Hadoop is the centerpiece of these platforms. Server-Side Java This practical guide is filled with examples which will show you Python how to successfully build a data platform using Hadoop. Step-by- PHP step instructions will explain how to install, configure, and tie all major Hadoop components together. Span and other inline elements This book is ideal for database administrators, data engineers , and system administrators, and it will act as an invaluable reference if you are planning to use the Hadoop platform in your organization This book can be purchased on the Amazon , Barnes and Noble or the Packt Publishing form example website. Motorbike Customer requirement Customer Details Name: E-mail: Phone number: Date of birth: list example Male Female Lists in HTML Do you own a Motorbike Yes No Client-Side Select the motorbike manufacturer HTML CSS JavaScript Honda Ducati Kawasaki semantic elements - header and footer: , Yamaha Aprilia navigator element: standalone article: , aside: placeholder and autofocus: , Customer Feedback Name: Placeholder and Autofocus E-mail: Please type in your feedback The Placeholder Attribute Enter the name of the animal in the search box below and click on Go Animal Name : The Autofocus attribute Login Name : or Login Id : HTML5 Music : required: Required attribute The Required Attribute Login name : search Search Search Input type Enter the search string in the textbox below and click on Go Packt Search : datalist for drop-down menu: Datalist : the new form attribute The Datalist Attribute Genres of Music Select Date email and url Input types: Email and URL Enter your email address in the textbox below and click Go multimedia: video Enter the web address (URL) of the website in the textbox below and click Go Video Player in HTML5 video { box-shadow:0 0 15px navy; border-radius:17px; } HTML5 Video Player date and month: can be done by JavaScript, jQurey, and HTML5 Date Input type Play Input type : Date Select an appropriate date from the datepicker below selectors: element, ID (with prefix “#” and unique), or class (with prefix “.”); we Pause can also group and nest selectors within one another Vol+ Vol- #pubman {color: red;}.packt {color: navy;} Packt, Always finding a way Packt Publishing : Packt Online Library: Packtlib fonts and text font-family: ‘Times New Roman’, Times, serif; font-style: normal; (or italic, oblique) font-size: 2em; font-weight: bold; (or normal) Introduction to CSS text-align: left; (or right, center, justify) CSS was introduced with HTML 4.0 and intended to take styling out from HTML text-index: 50px; structural markup (separate presentation from content), store in a separate file text-transform: uppercase; (or lowercase) and include in the document using a link tag text-decoration: line-through; (or line runs over, under, or through) incorporate CSS in HTML in the following ways: anchor pseudo classes inline styles: define CSS within the HTML tag; be used only when there is no other way of applying CSS a:link {color: blue;} a:visited {color: lime;} content a:hover {color: orangered;} internal styles: define styling for the whole page element border border-style: dotted, solid, or dashed element { color: color;} border-width: border-radius: defines the curvature of the border border-color: external stylesheets: the preferred way to incorporate CSS in HTML p { border-style: dotted; border-width: 2px; border-color: lime; border-radius: 25px; display:inline; margin: 25px; import command: create a new stylesheet change.css and invoke the padding: 10px 10px; stylesheet using the import command; this way, only the first page is } affected @import url(change.css); margin and padding: margin is the space outside any defined element, whereas css file structure: padding is the space inside any defined element selector { property: value;} p { Introduction to JavaScript background-color: lime; JavaScript is a single-threaded dynamic front-end language, it creates a single border-style:solid; display: inline; stack and doesn’t get run or executed until it is rendered in a web browser } #packt { JavaScript makes applications more responsive and improves user margin-top: 200px; experience; JavaScript is slow, block everything else until it’s finished; margin-right: 50px; exposed security flaws margin-bottom: 20%; synchronous or blocking vs. asynchronous or non-blocking: traditionally, margin-left: 150px; JavaScript was intended for adding simple functionality and minimal } runtime inside the browser, but modern browsers have been successful in display property: implementing web workers, a multithreaded JavaScript none: the element will be hidden and will not take up any space in the JavaScript supports procedural, object-oriented, and functional programming window. It will not affect the layout first-class functions: JavaScript functions can be referenced to a variable inline: element consumes space that is necessary (based on its content) and within its scope, assigned, passed as an argument, and returned as a result. does not include a line break callback is a chief functional programming technique that provides the block: elements are those that take the complete width along with a line flexibility of passing a function as an argument to another function break incorporated in it using too many callbacks gives rise to callback hell positioning: relative or absolute (http://callbackhell.com) and to avoid this, the promises library is used. JavaScript is a dynamic language and the three main functions are: float: move the elements to the left or right, position images and wrap the text around it, positioning elements in a web page, useful as block elements will not modifying HTML: adding to, inserting, and removing HTML; control CSS by line up beside one another, content can be wrapped around the floating element changing style properties or adding or removing attributes; inject more JavaScript into a document img { border: dashed; communicating with the server (e.g., with Ajax): able to refresh parts of a float:right; page on-the-fly } storing data at the client side: from simple variables to local databases progressive enhancement: the fundamental base for all front-end development, even an inline element will turn into a block-level element if the float a guiding principle that stress the important of content, a layered approach property is assigned to it. (structure, presentation, behavior) focus on content, the user, and accessibility the clear property in CSS is used with float when there is a need to clear structure (html): heading (with ), paragraphs (with ), floated elements on the left or right-hand side of an element to make them navigation (with ), , , , lists, aligned correctly presentation (css for performance): inline CSS is only applied to elements.packt { that cannot be cached and cannot be reused), keep CSS out of your HTML float:left; (external CSS); applying styles through meaningful hooks you left in the border: solid; HTML-like classes, IDs, and even normal HTML elements margin:10px; behavior (JavaScript): to smooth out interactions, make Ajax calls, slide } elements around a page, and modify HTML; use embedded JavaScript #pub { instead of inline JavaScript and link JavaScript file at the bottom of the clear: both; margin-top: 2px; document (put a reference at the top of the document only to set margin-bottom: 4px; up any object initializations); the files will load in the order they are listed, } and adding the library to the top of the list ensures that anything below it can access the dependencies content is more important than decoration, keep layers separated (also in string with property.length (throws an error to get the length of a separated files) for reusability, accessibility for disabled users, graceful null or undefined string) degradation for browser versions, to be sure your content is accessible and your concatenation operator +: you can prefix all with “” to force mixed applications are usable without JavaScript turned on type conversion Web standard works on across browsers for consistent user experience: FCMA functions indexOf(), lastIndexOf(), substr() or substring(), slice(), International (https://github. com/tc39/ecma262) releases ECMAScript versions split(), trim() (for V8 JS), charAt(), charCodeAt() for Unicode, that progress from Stage 0 (where input is allowed into the specification) until includes(), startsWith(), endsWith(), toLowerCase(), toUpperCase() Stage 4, where the proposed addition has been formally accepted to go into the regular expression using literal format inside // or new RegExp(), next version of the standard and functions replace(), search() a reusable JavaScript code is a package; the developers share their own packages string padding: padStart(), padEnd() on the NPM repositories; NPM provides a platform to store, browse, and access If you are saving HTML to strings a lot, single quotes may save you these packages among developers https://docs.npmjs.com/files/package.json some time because you won’t have to escape all the double-quoted libraries and utility modules on NPM are already maintained and optimized attribute values in HTML by developers, rather than writing boilerplate code of our own, using the console.log(1.padStart(10)); library is recommended with respect to its use and performance efficiency. " 1" Suggested directory structure console.log('1'.padEnd(10, "0")); "1000000000" template strings for string interpolation/substitution: ${} var person = { name: "Gabriel", age: "33", profession: "developer", saySomething: function msg(d){ return "This is my message: " + d } }; console.log( `My name is ${person.name} and I'm a ${person.profession}. ${person.saySomething("Happy Tuesday!")}` ); types tagged templates allow us to take different actions on literals and core types: recommend use the primitive types whenever possible values: using backticks, used to sanitize input from a form and number (64-bit IEEE 754 float with 53-bit accuracy) avoid a SQL injection or a cross-side scripting (XSS) attack functions parseInt() and parseFloat() to convert strings to numbers: function namesToUpper(strings,...values) { may return NaN (not-a-number) for failing to convert; and use return strings.reduce(function test(a, b, c) { isNaN() to check; function isInteger(),.prototype.toFixed(n) return ${a}${values[c - 1].toUpperCase()}${b}; }) boolean: true or false } 0, empty strings (""), NaN, null, and undefined all evaluate to false, var fName = "Gabriel"; all other values evaluate to true var mName = "Alejandro"; Function toString(), valueOf() var lName = "Cánepa"; string using single or double quotes with escape sequence \ console.log(namesToUpper `First Name: ${fName}, Middle Name: strings are sequences of Unicode characters (represented ${mName}, Last Name: ${lName}`); internally in a 16-bit UCS-2 format, and Node.js will convert to UTF- 8 for interacting with the outside world) arrow functions for shorter syntax and allow inherit the this value from the enclosing context function Counter() { Object(); property.values(),.entries(); performance concerns on deeply this.value = 0; nested objects (consider non-object-oriented approach instead) var timer = setInterval(() => { Date object created by new Date(): function getDate(), getDay(), this.value++; getFullYear(), getHours(), getMinutes(), getMonth(), getSeconds(), console.log(this.value); getTime(), toString() if (this.value >= 5) { complex types: function, array (multidimensional array and clearInterval(timer); associative array) } }, 1000); array: a collection of (mixed) typed values, literal syntax [] or } new Array(), 0 indexed, dot notation property (fixed values or var p = new Counter(); methods).length, delete command (still “exist” and set to class undefined), function Array.isArray(), push(), pop(), shift(), class Employee { unshift(), includes(), join() (with a separator), splice() (with constructor(hireDate, monthlySalary) { starting/ending position and same for removing), forEach(), this.hireDate = hireDate; sort() (alphabetical or custom sorting with optional sorting this.monthlySalary = monthlySalary; function to sort as parameter), concat() } > var names = [ 'marc', 'Maria', 'John', 'jerry', 'alfred', getMonthlySalary() { 'Moonbeam']; return `I make ${this.monthlySalary} each month.` undefined } > names.sort(); [ 'John', 'Maria', 'Moonbeam', 'alfred', 'jerry', 'marc' } ] class Person extends Employee { > names.sort(function (a, b) { constructor(fName, lName, profession, age, hireDate, var a1 = a.toLowerCase(), b1 = b.toLowerCase(); monthlySalary) { if (a1 < b1) return -1; // Properties if (a1 > b1) return 1; super(hireDate, monthlySalary); return 0; this.fName = fName; }); this.lName = lName; [ 'alfred', 'jerry', 'John', 'marc', 'Maria', 'Moonbeam' this.profession = profession; ] this.age = age; > } functions are fully typed objects that can be manipulated, // Methods extended, and passed around as data; functions with static saySomething() { scoping return `What's up? I am a ${this.age}-yr. old functions can return a single value or an array of values ${this.profession} and was hired on ${this.hireDate}.`; alert() method displays arguments in the form of a pop-up } box in the browser } anonymous function performs better than a normally defined var me = new Person("Gabriel", "Cánepa", "developer", "33", "2016-03- 22", 1575); function because there is nothing to reference; anonymous console.log(me.saySomething()); function may make debugging difficult console.log(me.getMonthlySalary()); special kinds of objects: null, undefined, and Infinity and -Infinity object (associative array, hash map, or dictionary), the extremely (e.g., for dividing by 0 instead of generating a runtime exception) dynamic and flexible data type using object literal syntax {} or new you can add a new property to an object using “.”, remove a property using delete keyword, accessing a non-exist property gets undefined function Object.keys(), and property.length var s = new Shape(); reserved keywords (identifiers) and variables are case-sensitive: break, case, s.move(10, 10); console.log(s.distance_from_origin()); catch, continue, debugger, default, delete, do, else, finally, for, function, if, function Square() { implements, in, instanceof, interface, new, package, private, protected, } public, return, static, switch, this, throw, try, typeof, var, void, while, with Square.prototype = new Shape(); declare a variable with var keyword, but if without var (not Square.prototype.__proto__ = Shape.prototype; recommended) is global Square.prototype.Width = 0; Square.prototype.area = function () { local variables using let keyword return this.Width * this.Width; closure: variable scope traveling downhill/cascading inside a containing } function var sq = new Square(); typeof operator sq.move(-5, -5); type comparison sq.Width = 5; console.log(sq.area()); equality operator == for having the same value console.log(sq.distance_from_origin()); precise equality operator === for having the same value and same type function Rectangle () { type conversion } toUpperCase(), toLowerCase() Rectangle.prototype = new Square(); language constructs Rectangle.prototype.__proto__ = Square.prototype; Rectangle.prototype.Height = 0; assignment: =, +=, -=, *=, /=, ++, -- Rectangle.prototype.area = function () { operator: logic, mathematic (+, -, *, /), ternary, bitwise (and &, or |, inverse return this.Width * this.Height; ~, and xor ^ by first converting into 32-bit integers, performing operation, } and converting back to a JavaScript number)) var re = new Rectangle(); comparison: =, , >=, ==, ===, !=, !== re.move(25, 25); conditional: if, then, else, switch-case (with break and default) re.Width = 10; re.Height = 5; loop: for loop, while loop, do … while loop, for … in loop, foreach loop console.log(re.area()); object-oriented: all classes are declared as function console.log(re.distance_from_origin()); use “this” inside classes, you can add properties and methods to classes console.log(sq instanceof Square); // true by default, all objects have a prototype object for inheritance, a new console.log(sq instanceof Shape); // true console.log(sq instanceof Rectangle); // false class you are declaring should have the base prototype of the specified console.log(re instanceof Rectangle); // true type, and then you can extend it from there console.log(sq instanceof Square); // true function Shape () { console.log(sq instanceof Shape); // true } console.log(sq instanceof Date); // false Shape.prototype.X = 0; Shape.prototype.Y = 0; variables can hold values, objects, or even functions; they can change, they can Shape.prototype.move = function (x, y) { be static, and they can even be empty this.X = x; constant: use uppercase letters and variable declarations this.Y = y; local variables are defined within a function and always prefaced using “var” } when they’re defined with or without initialization Shape.prototype.distance_from_origin = function () { return Math.sqrt(this.X*this.X + this.Y*this.Y); global variables have unique names to prevent naming collisions and can be } defined three different ways: Shape.prototype.area = function () { defining them with “var” outside a function throw new Error("I don't have a form yet"); adding something directly to the window object } defining them anywhere without using “var” errors and exceptions var msg = "this is from a variable"; function uhoh () { console.log(msg); throw new Error("Something bad happened!"); tools built into the browser: } YUI Compressor (www.refresh-sf.com/yui/) remove all whitespace from function uhoh () { code to improve performance by reducing the file size (also keep an throw new Error("Something bad happened!"); uncompressed version of the file) } try { minification: remove whitespaces from development files to uhoh(); production files on server-side, and then files are concatenated and } catch (e) { shrunk down to a single line console.log("I caught an error: " + e.message); JSLint (http://www.jslint.com) looks for syntax and formatting problems } eval() method: evaluating and executing any string that is passed into it as an console.log("program is still running"); argument, this makes the method extremely insecure and very likely one of the many JavaScript errors go overlooked because, if built correctly, everything largest security holes in the entire language, e.g., injection hacks; use will still work fine; this can be a double-edged sword JSON.parse() instead of eval() comments: single-line comments start with //, multiple line comments enclosed popular interaction on the web: hide/show example inside HTML use strict: the parser uses stricter rules when executing your script creating fallbacks: allows you to use cutting-edge coding practices while still offering less-cutting-edge technologies failing quickly: if statements or conditionals to constantly check the state of Click to Hide something go wrong Hide the text Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi dolor metus, sagittis et aliquam et, ornare et libero. Etiam eu nisi felis, ac posuere metus. Vivamus molestie bibendum imperdiet. Etiam et faucibus metus. if(typeof window.localStorage !== "undefined"){ // use localStorage CSS } else {.hide { // use normal cookies display: none; } } tools built into the language: use JavaScript console to output messages for JavaScript debugging, monitoring errors, and Ajax interactions var button = document.getElementById("hide"), console.log("hello there"); target = document.getElementById("target"); function hide(){ target.setAttribute("class","hide"); jQuery each() method (slow, better use native loop instead): loop } through and output the data that is returned button.addEventListener("click", hide, false); function chaining allows you to add an endless amount of methods to a single DOM node, e.g., using the parents() method in conjunction with JavaScript libraries/tooltits/frameworks: addClass() library for cross-browser-tested methods YUI (yuilibrary.com) is a free and open source JavaScript and CSS framework scalable for large Web applications; it contains the YUI JavaScript Library, Deep Dive JavaScript the YUI CSS Library, and other tools such as the YUI Online Code Compressor, universal document object model (DOM): a mapping layout model for structure which will safely minify your code for you of the document; the DOM is an outline of the HTML document you are jQuery (jquery.com) is used on more than 50% of all the top websites; accessing; there are top-level items, items nested under them, and items the ready() methodis bound to the document and takes a single argument, grouped in chunks; every node in the DOM has a relationship (parent, child, which is the entirety of the JavaScript you’re attaching to the HTML sibling) to its surrounding nodes; performance in JavaScript is a constant issue, document especially when moving through the DOM jQuery selector: a dollar sign ($) and parentheses surrounding the DOM tree starts with the Web browser; when you visit a website, the the document declaration; the selector $(“.module”) behind the scenes browser renders the HTML into a document, reads through the elements, the library is running through feature detection checks against the and displays them to the user in the correct format browser you’re using to see which native method it should use for the nodes that represent HTML elements are called element nodes, ones that highest efficiency possible represent text are called text nodes and last are attribute nodes; the overall Sizzle selector engine allows you to use CSS syntax to select elements in parent document node the DOM jQuery has four methods of traveling around the DOM: parent()—Get the immediate parent node. parents()—Look through all parent nodes until you find a selector match (can travel multiple levels). find()—Travel down the DOM until you find a match (can travel multiple levels). siblings()—Get sibling elements that match the selector. addClass() method: add a class to the selected element first(), last(), next() and prev() methods jQuery makes adding style information to a DOM node very easy with the css() method types of nodes: access them differently when traveling throughout the DOM combine events and the css() method syntax to create JavaScript animations using animate() method element nodes method: the ajax() object in jQuery offers up an extremely flexible API where you an element’s ID value must be unique to the document, only one can easily set configurations for your call, whether it’s a GET or POST, ID per page, using an element’s ID as the document access point using JSON, HTML, XML or script; options for accepting callbacks in the with getElementById(); although we are using the ID attribute to case of a successful call or a failed call; API methods to check the status access the node, we are still accessing the element node and not of an Ajax call: error(), success(), and complete() the attribute node parse JSON data: getJSON() takes two arguments, a URL to the JSON use getElementsByTagName() and getElementsByClassName() to data, and the function you want to execute upon a successful data get a NodeList, i.e., a collection of nodes that maintain their source return order; to pull an item out of the NodeList, use item() or using array or an anonymous function, and a boolean capture which is 99% false (setting syntax [] to true means event propagation which announces to all the parent DOM Sizzle Selector Library method querySelector() will return only the nodes that an event is firing on a particular node first element that it comes across, and querySelectorAll() will event binding: binding (attaching) events to DOM elements and calling return a NodeList functions inside the addEventListener() method attribute node method: hasAttribute(), getAttribute(), setAttribute(), we can’t pass any arguments into an anonymous function, in order to removeAttribute() pass arguments into a function while using addEventListener(), you text node: innerHTML is a lot faster to wipe out a large chunk of need to use the function as a callback instead by nesting it inside an information than it is to do the same thing on each individual DOM node anonymous function you want to replace // save the DOM element you want to attach an event to navigation method: parentNode, firstChild, lastChild, previousSibling, var btn = document.getElementByID("btn"); // define your function normally nextSibling function alertMessage(message) { dynamic method: createElement(), createTextNode(), appendChild(), alert(message); removeChild() } storing data in JavaScript: make it well organized and easy to access, either // or use a predefined function (event handler), "alertMessage" internal to your own personal scripting file or externally generated data btn.addEventListener("click", function() { // callback function! produced by a database local to your application or an external API service alertMessage("clicked the button"); client-side storage }, false); browser cache detaching events: unbind (detach) events from DOM nodes using JavaScript variables, arrays, objects: When you declare a variable, it is removeEventListener() with same 3 arguments as addEventListener() cached two ways to tell if an element if clickable, e.g., heading (H1) is clickable cookies (used on both the server and the client) store data locally in the turn off all CSS and JavaScript in the browser and click it; if something user’s browser: can be turned off by the user happens, you have a clickable element HTML5 localStorage and sessionStorage method: setItem() with 2 tab through an interface and press Enter/Return when you get to that arguments of a variable label and a string value, getItem() and element removeItem() both with an argument of the name of the item; events and attached functions include load, click, dblclick, mousedown, localStorage will remain active until explicitly removed or the user, via mousemove, mouseout, mouseover, mouseup, keydown, keypress, keyup, the browser preferences; sessionStorage will remove itself at the end blur, focus, submit, touchstart, touchend, touchmove, touchcancel, of each browser session (when the browser is closed) orientationchange, gesturestart, gestureend, gesturechange interacting with the user through events focus and blur events are mostly related to forms and links; tab through a event-driven JavaScript: events are triggered in the browser when page, if you can reach the element you want, then it is focusable something happens and events need to be attached to DOM elements to be link and form input elements (text inputs, radios, check boxes, buttons) executed, e.g., “load” is an event that fires when a page is first loaded; a are all focusable elements user clicking a link, Click is another event context highlighting: bringing attention to a certain area of a form by Event handlers: attaching only a single function to a specific event of a DOM changing background color, e.g., whenever a user focuses on the search element node; when using event handlers, the normal event you would field, we are going to add a class of “active” on the parent element attach is always prefaced with the word “on”, e.g., onclick, onsubmit, (), which we have already added CSS for to set a background color onchange, onfocus, onblur, onmouseover, onmouseout, ontouchstart, change event: in radios and check boxes, a change value is triggered when ongesturestart the box/button is checked; In a select menu, the change event is triggered Event listeners can assign multiple functions to the same DOM element and when a new value or option is selected by clicking or by keyboard navigation event using addeventListenter() with 3 arguments: an event type, a function mouseover and mouseout (hovering): the mouseover event triggers when a target = document.getElementById("output"); user positions a cursor over an element; mouseout triggers in the opposite var addr = { case, when the user removes the mouse cursor from the same element; the search : function(event) { combination of these two events creates a complete hover effect // save the input value, contacts length and i to preventing default behavior is something you often need to do when // variables executing JavaScript on DOM elements that have another behavior attached var searchValue = searchField.value, to them: you first need to pass the event (form submit in our case) as an i; argument into the method. Then attach the preventDefault() method to it // stop the default behavior event.preventDefault(); keydown, keypress, and keyup: keydown is the initial press, keyup is when // clear the target area just in case there's the finger is lifted, and keypress is somewhere in the middle; keyup is the // something in it. most popular of the three events target.innerHTML = ""; code example // check the count, of course // loop through the contacts (function() { for(i = 0; i < count; i = i + 1) { // look through the name value to see if it var contacts = { // contains the searchterm string "addressBook" : [ var obj = contacts.addressBook[i], { isItFound = "name": "hillisha", obj.name.indexOf(searchValue); "email": "[email protected]", // anything other than -1 means we found a }, // match { if(isItFound !== -1) { "name": "paul", target.innerHTML += '' + obj.name + ', "email": "[email protected]", '+ obj.email +''; }, } // end if { } // end for loop "name": "vishaal", } // end count check "email": "[email protected]", }, }, getAllContacts : function () { { var i; "name": "mike", // clear the target area just in case there's "email": "[email protected]", // something in it. }, target.innerHTML = ""; { // check the count, of course "name": "jamie", if(count > 0){ "email": "[email protected]", // loop through the contacts } for(i = 0; i < count; i = i + 1) { ] var obj = contacts.addressBook[i]; }; target.innerHTML += '' + obj.name + ', 0) { target = document.getElementById("output"); // loop through the contacts for(i = 0; i < count; i = i + 1) { var addr = { // look through the name value to see if it contains search : function(event){ // the searchterm string var obj = addrBook[i]; var output = document.getElementById("output"); target.innerHTML += '' + obj.name + ', '+ obj.email +''; ajaxCall('data/contacts.json', output, function (data) { } // end for loop // save the input value, contacts length and i to } // end count check // variables }); // end ajax call var searchValue = searchField.value, }, addrBook = data.addressBook, setActiveSection : function() { count = addrBook.length, // add a class of "active" to the wrapping div i; this.parentNode.setAttribute("class", "active"); // stop the default behavior }, event.preventDefault(); removeActiveSection : function() { // clear the target area just in case there's something // remove the class from the wrapping div // in it. this.parentNode.removeAttribute("class"); target.innerHTML = ""; }, // check the count, of course addHoverClass : function() { if(count > 0 && searchValue !== ""){ // remove the class from the wrapping div // loop through the contacts searchForm.setAttribute("class", "hovering"); for(i = 0; i < count; i = i + 1) { }, // look through the name value to see if it contains removeHoverClass : function(){ // the searchterm string // remove the class from the wrapping div var obj = addrBook[i], searchForm.removeAttribute("class"); isItFound = obj.name.indexOf(searchValue); } // anything other than -1 means we found a match } // end addr object if(isItFound !== -1) { // activate auto complete on keyUp target.innerHTML += '' + obj.name + ', '+ obj.email +''; // set active section on focus of the form field } // end if searchField.addEventListener( } // end for loop "focus", addr.setActiveSection, false); } // end count check // remove active section on blur of the form field }); // end ajax call searchField.addEventListener( }, getAllContacts : function () { "blur", addr.removeActiveSection, false); highly focused microlibraries with little code wasted and not used; // get all contacts when you click the button when building a project using multiple microlibraries, you will need to make getAllButton.addEventListener( "click", addr.getAllContacts, false); sure they all work well together // add hover class on mouse over of the form field HTML5 JavaScript APIs searchForm.addEventListener( creating more meaningful content wrappers: using more semantic "mouseover", addr.addHoverClass, false); or than meaningless layout element , using and // remove hover class on mouse out of the form field for document, using and in data tables searchForm.addEventListener( "mouseout", addr.removeHoverClass, false); landmark role for ARIA to represent navigational landmarks in the // activate search on form submit document: application, banner, complementary, contentinfo, form, searchForm.addEventListener("submit", addr.search, false); main, navigation, search })(); // end anonymous function abstract roles: command, input, range extending libraries through plug-in widget roles: alertdialog, menu, menuitem, progressbar a plug-in is a built-in way to extend the functionality of a library document structure roles: article, definition, heading, math converting a function into a jQuery plug-in: includes the plug-in name, default options, options that the user can overwrite, a loop, and the actual striping code from the zebraStripe() function // enclose the plug-in so no variables leak out Chapter 11 (function($){ // define and name the plug-in $.fn.zebraStripe = function(options) { // define default options var defaults = { elToStripe: "tr" Site title }; Site slogan // let options be customized by the user var options = $.extend(defaults, options); // loop through each element you're attaching the // plug-in to return this.each(function() { Home Blog // use the attached element and option value $(this).find(options.elToStripe + ':odd').css({ Portfolio 'background': '#ccc' Contact }); }); // end loop }; })(jQuery); $(document).ready( function () { // attached zebra strip plug-in to the #output div $('#output').zebraStripe({ elToStripe: "tr" // if you want to change the option // (we didn't) }); JavaScript APIs for location-based services, media embedding, and server }); // close document.ready communication navigator object (a root-level object) with helpful information: browser using default control or remotely create actions like: play, pause, name, browser version, platform, if cookies are turned on or off, if Java volume up, and volume down is enabled, user agent string Normal Audio Element with Standard Attributes geolocation: the capability of grabbing a user’s IP address, running it through some process on the server, and outputting the user’s general location for serving up ad information, alerting users of businesses within walking distance, etc.; the getCurrentPosition() method returns HTML Structure for Creating Custom Audio Controls information including latitude and longitude, position accuracy reported in meters, altitude, altitude accuracy reported in meters, heading, and speed (function () { Chapter 11 - Audio and Video // define a function to output all the data returned from // navigator.geolocation function getPositionData(position) { var body = document.getElementsByTagName("body"); body.innerHTML += "Latitude: " + position.coords.latitude + ""; body.innerHTML += "Longitude: " + position.coords.longitude + ""; body.innerHTML += "Position accuracy (in meters): " + play/pause position.coords.accuracy + ""; volume up body.innerHTML += "Altitude: " + volume down position.coords.altitude + ""; body.innerHTML += "Heading: " + position.coords.heading + ""; body.innerHTML += "Speed: " + position.coords.speed + ""; } // end success function Creating Custom Controls for Audio or Video Elements if(navigator.geolocation) { (function () { // using getCurrentPosition to return positioning data var player = document.getElementById("player"); navigator.geolocation.getCurrentPosition( // play or pause the audio file getPositionData); function playPause() { } else { // if the audio is paused, play it // apologize to the user for teasing them if (player.paused) { alert("sorry, this browser doesn't support the player.play(); Geolocation PI"); // if the audio is playing, pause it } // end support check } else { })(); // End anonymous function player.pause(); geosecurity: implemented a permissions system to deal with } geolocation in the form of a pop-up message asking for permission to } get the user’s current location // turn down the volume by.1 each time embedding audio and video into an HTML document using and function volumeDecrease () { // check to see if the volume is already all the way down if(player.volume >.1) { with stacking multiple elements to let the browser travel player.volume -=.1; down the list and play whichever format it supports. If it supports } else { multiple formats listed, it will take the first one it hits alert("minimum volume level"); } } // turn up the volume by.1 each time Example of Implementing the History API with Ajax function volumeIncrease () { (function(){ // check to see if the volume is already all the way up var links = document.getElementsByTagName('a'), if(player.volume 0) { } // loop through all the links on the page } for (i = 0; i < linkCount; i = i + 1) { // set up your listeners var obj = links[i]; document.getElementById("play").addEventListener( // attached a click event to each link 'click', playPause, false); obj.addEventListener('click', function(e) { document.getElementById("vol-up").addEventListener( e.preventDefault(); 'click', volumeIncrease, false); // store the href and text of the link you document.getElementById("vol-down").addEventListener( // clicked 'click', volumeDecrease, false); var href = this.getAttribute("href"), })(); title = this.innerHTML; the History API allows you to manipulate the browser’s address bar and // push the new URL in to the address bar history contents by allowing meaningful (and real) URLs to be pushed history.pushState(href, title, href); into the address bar and maintained in the browser history (both // make the ajax call to get the HTML snippet in // the page forward and back) ajaxCall(href, output, function (data) { the pushState() method extended the history object to change the output.innerHTML = data; address bar URL and load in the contents of the URL that is being }); pushed by an Ajax call that is to be executed when a link is clicked }, false); popstate listens for the back and forward buttons to be activated; } // end loop when this happens, you can access the data previously stored in } // end counter check })(); the history object (the URL you want) and create another Ajax call Ajax Function to load in the appropriate content function ajaxCall(dataUrl, outputElement, callback) { HTML Documents to Show the History API var request = getHTTPObject(); outputElement.innerHTML = "Loading"; Chapter 11 - History API request.onreadystatechange = function() { // check to see if the Ajax call went through if ( request.readyState===4 && request.status===200 ) { // save the ajax response to a variable var data = request.responseText; Cats | // make sure the callback is indeed a function before Dogs | // executing it Birds if(typeof callback === "function"){ callback(data); } // end check } // end ajax status check } // end onreadystatechange request.open("GET", dataUrl, true); (function () { request.send(null); // create a new instance of the worker Activating the Back Button with the History API var worker = new Worker("js/worker.js"); // listen for the popstate event (forward and back buttons) var btnStart = document.getElementById("start"), window.addEventListener("popstate", function(e) { btnStop = document.getElementById("stop"), // access the history state (the URL that was saved) timerOuput = document.getElementById("timer"), var storedHistoryData = e.state; workerOutput = document.getElementById("output"), // make the ajax call to get the HTML snippet in the page num = 0; ajaxCall(storedHistoryData, output, function (data) { // create a script that is constantly running to block the output.innerHTML = data; // normal flow }); setInterval(function () { }); // end listener event num = num + 1; web workers supplement the server communication model by opening timerOuput.innerHTML = num; }, 500); up a secondary thread in which you can pass data back and forth // add click event to the start button to activate the worker through; web workers live in a separate JavaScript file, which is btnStart.addEventListener("click", function() { referenced from the main JavaScript file; because of security concerns, worker.postMessage(contacts); // send contacts data to workers do not have access to the DOM; their sole purpose is to fetch // the worker and return data to the main file; Web workers open up a new method }, false); and a new event: // set up message listener worker.addEventListener("message", function(e) { postMessage() is used on both sides; workerOutput.innerHTML += e.data; the message event is triggered after the postMessage() method is }, false); called; the receiving file will wait for the message event to trigger // add a click event to the stop button to terminate the an action // worker we will set up three event listeners: a normal click event that will btnStop.addEventListener("click", function() { worker.terminate(); start the worker calling the postMessage() method on the worker btnStart.setAttribute("disabled", "disabled"); instance, utilizes the message event to wait for a reply from the alert("worker has been terminated"); worker, and terminate the worker and add a disabled attribute to }, false); the start button })(); HTML Document to Display Web Worker Functionality worker Script in worker.js (function(){ // set up an event listener to catch the message addEventListener("message", function(e) { Chapter 11 - Web Workers var data = e.data.addressBook, dataCount = data.length, counter = 0; // send the data every half second until it reaches the start worker // end stop worker setInterval(function(){ if(counter < dataCount){ ostMessage("" + data[counter++].name + ""); } }, 500); }, false); })(); main JavaScript Contents in html5.js if(battery) { battery.addEventListener( "chargingchange", updateBatteryStatus); battery.addEventListener( "levelchange", updateBatteryStatus); updateBatteryStatus(); } })(); In Firefox the battery object is navigator.mozBattery, and in Chrome/Safar it is navigator.webkitBattery vibration API: provides you programmatic access to the vibration mechanism of a device only with a vibration mechanism (function(){ device API: narrow the gap between building a native device application and // attach a click event to a button with an ID of "vibrate" developing purely on the Web document.getElementById("vibrate").addEventListener("click", battery status API as part of the System Information API specification to function(){ retrieve the battery life and status of a device from the browser for if(navigator.vibrate) { // vibrate for 1 second wait half a second, then defer or scale back excess processing using setInterval() to adjust the // vibrate 2 seconds amount of Ajax calls to the server; the API will return four types of navigator.vibrate([1000, 500, 2000]); information: } else { battery level (number from 0 to 1) // apologize to the user for teasing them battery charging status (true or false) alert("sorry, this browser doesn't support the battery charging time (how long until the battery is fully charged) vibrate API"); } // end support check battery discharge time (how long until the battery is dead) }, false); each piece of information can be accessed through the navigator object, })(); like navigator.battery.level; this API also opens up four new JavaScript network information API provides access to information about the events to constantly monitor the battery status: underlying connection of a device; if the available bandwidth doesn’t chargingchange (when the level increases) lend well to large graphics, we can load images that are more chargingtimechange (when charge time changes) appropriate for the data exchange rate; navigator.connection.type dischargingtimechange (when discharge time changes) returns a numerical value, which maps to a connection speed; the levelchange (whenever the battery level changes) connection speed is either unknown, Ethernet, or WIFI (0, 1, 2 (function(){ type codes) var battery = navigator.battery, HTML Document to Show Off the Network Information API body = document.getElementsByTagName("body"); function updateBatteryStatus() { body.innerHTML += "Battery level: " + battery.level * 100 + "%"; Chapter 11 - Network Connection body.innerHTML += "Battery is charging: " + battery.charging + ""; body.innerHTML += "Battery charging time: " + battery.chargingTime + ""; body.innerHTML += "Battery discharging time: " + battery.dischargingTime + ""; } // detect if the battery status API is supported Checking the Network Connection to Load Larger Images bootstrap-grid.css Only — — Only flex (function (){ bootstrap-grid.rtl.css grid utilities // Check bandwidth level is supported bootstrap-grid.min.css system var connection, bootstrap-grid.rtl.min.css connectionSpeed, images = document.querySelectorAll("img[data-large]"), bootstrap-utilities.css — — — Included imageCount = images.length, bootstrap-utilities.rtl.css i; bootstrap-utilities.min.css // create a custom object if navigator.connection isn't bootstrap-utilities.rtl.min.css // available bootstrap-reboot.css — Only — — connection = navigator.connection || { 'type': '0' }; bootstrap-reboot.rtl.css Reboot if(imageCount > 0 && connection.type === '0' || connection.type === '1' || connection.type === '2') { bootstrap-reboot.min.css for (i = 0; i < imageCount; i = i + 1) { bootstrap-reboot.rtl.min.css var obj = images[i], largeImg = obj.getAttribute('data-large'); JS Files Popper Introduction to Bootstrap bootstrap.bundle.js Included Bootstrap is a free front-end framework includes HTML and CSS based design bootstrap.bundle.min.js templates for typography, forms, buttons, tables, navigation, modals, image bootstrap.js – carousels and many other, as well as optional JavaScript plugins bootstrap.min.js CSS is smaller, faster, and easier to use than Bootstrap creating web sites which automatically adjust themselves to look good on all { either download Bootstrap from getbootstrap.com or include Bootstrap from a "imports": { CDN (Content Delivery Network) "@popperjs/core": "https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/esm/popp