JavaScript Implementations PDF
Document Details
Uploaded by SolidQuasimodo
Tags
Summary
This document comprehensively covers fundamental JavaScript concepts. It details the various object models like DOM, Window, Location, Navigator, and Screen, along with their specific properties and functionalities. The document also explains how to work with these concepts in web development.
Full Transcript
JAVASCRIPT IMPLEMENTATIONS Basic DOM Model for Browsers THE WINDOW OBJECT Window object properties are available in the global scope=> browser APIs it as an access point. Window object’s properties drastically diverge between browsers due to differing vendor implementations. The Global...
JAVASCRIPT IMPLEMENTATIONS Basic DOM Model for Browsers THE WINDOW OBJECT Window object properties are available in the global scope=> browser APIs it as an access point. Window object’s properties drastically diverge between browsers due to differing vendor implementations. The Global Scope of Window=> all variables and functions declared globally (using var) are properties and methods of the Window object. innerWidth, innerHeight indicate the size of the page viewport inside the browser window (minus borders and toolbars). outerWidth, and outerHeight. outerWidth and outerHeight return the dimensions of the browser window itself. The browser window can be resized using the resizeTo(x,y) and resizeBy(x,y) methods. To navigate to a particular URL and to open a new browser: window.open("http://www.ase.ro/", "topFrame"); THE LOCATION OBJECT Location provides information about the document that is currently loaded in the window, as well as general navigation functionality. The location object is unique. It is a property of both window and document; both window.location and document.location point to the same object. PROPERTY NAME DESCRIPTION location.hash The URL hash (the pound sign followed by zero or more characters), or an empty string if the URL doesn’t have a hash. location.host The name of the server and port number if present. location.hostname The name of the server without the port number. location.href The full URL of the currently loaded page. The toString() method of location returns this value. location.pathname The directory and/or filename of the URL. location.port The port of the request if specified in the URL. If a URL does not contain a port, then this property returns an empty string. location.protocol The protocol used by the page. Typically "http:" or "https:". location.search The query string of the URL. It returns a string beginning with a question mark. location.username The username specified before the domain name. location.password The password specified before the domain name. location.origin The origin of the URL. Read only. THE NAVIGATOR OBJECT The navigator object properties which offer insight into system capabilities. PROPERTY/METHOD DESCRIPTION battery Returns a BatteryManager object to interact with the Battery Status API. connection Returns a NetworkInformation object to interact with the Network Information API. cookieEnabled Indicates if cookies are enabled. credentials A CredentialsContainer to interact with the Credentials Management API. deviceMemory The amount of device memory in gigabytes. doNotTrack The user’s do-not-track preference. geolocation A Geolocation object to interact with the Geolocation API. getVRDisplays() Returns an array of every VRDisplay instance available. getUserMedia() Returns the stream associated with the available media device hardware. languages An array of all the browser’s preferred languages. locks A LockManager object to interact with the Web Locks API. mediaCapabilities A MediaCapabilities object to interact with the Media Capabilities API. mediaDevices The available media devices. maxTouchPoints The maximum number of supported touch points for the device’s touchscreen. onLine Indicates if the browser is connected to the Internet. oscpu The operating system and/or CPU on which the browser is running. permissions A Permissions object to interact with the Permissions API. platform The system platform on which the browser is running. plugins Array of plug-ins installed on the browser. In Internet Explorer only, this is an array of all elements on the page. registerProtocol Registers a website as a handler for a particular protocol. Handler() requestMediaKey Returns a Promise which resolves to a MediaKeySystemAccess object. SystemAccess() sendBeacon() Asynchronously transmits a small payload. THE SCREEN OBJECT It provides details about client’s display outside the browser window. PROPERTY DESCRIPTION The pixel height of the screen minus system elements such as Windows availHeight (read only). The first pixel from the left that is not taken up by system elements (read availLeft only). The first pixel from the top that is not taken up by system elements (read availTop only). availWidth The pixel width of the screen minus system elements (read only). The number of bits used to represent colors; for most systems, 32 (read colorDepth only). height The pixel height of the screen. left The pixel distance of the current screen’s left side. pixelDepth The bit depth of the screen (read only). top The pixel distance of the current screen’s top. width The pixel width of the screen. orientation Returns the screen orientation as specified in the Screen Orientation API HTML as a Tree DOM Document Object Model (DOM) – a structured tree representation of a web page HTML of every web page is turned into a DOM representation by the browser DOM provides the way to programmatically access HTML structure in JavaScript The root DOM object => accessed by the document object All JavaScript objects generate the three Each element within the page is referred to as a node. Includes references to childNodes / children Includes references to (parentNode) and next node (nextSibling) Includes methods to manage the child node: appendChild(nod), removeChild(nod)… Nodes have specific methods and properties function on the related HTML tag. What does the DOM look like? HTML DOM Retrieving a DOM Node Nested objects are accessed using a dot notation. To access the first image in a document, using the index: document.images By element name: document.getElementsByTagName(HTML tag name) ->retrieves any element or elements you specify as an argument paragraphs = document.getElementsByTagName("p"); for( i = 0; i < paragraphs.length; i++ ) {// do something } By id attribute value: document.getElementById() By class attribute value: document.getElementsByClassName() By selector: querySelectorAll(CSS selector) allows to access nodes of the DOM based on a CSS style selector. b=document.querySelectorAll("button"); b.innerText; Accessing DOM Node’s Attributes Accessing attributes: elem.AttributeName – to refer to the individual attribute name elem.attributes – attribute collection elem.hasAttribute(name) – check the attribute availability elem.getAttribute(name) – get the attribute value elem.setAttribute(name, value) – set the attribute value elem.removeAttribute(name) – remove the attribute: Accessing CSS attributes: elem.style.CSSAtributeName elem.className - class string name as used in the HTML document elem.classList – object that allows accessing class list (add / remove / toggle / contains methods) Accessing DOM Node’ Attributes - Examples Accessing an attribute value: getAttribute(attribute name) ->to get the value of an attribute attached to an element node. img=document.getElementsByTagName("img"); img.getAttribute("src"); setAttribute(the attribute to be changed, the new value for that attribute) img.setAttribute("alt","New photo"); innerHTML – for accessing and changing the text and markup inside an element h2=document.getElementsByTagName("h2"); h2.innerHTML="Accommodation"; Note: innerHTML content is refreshed every time and thus is slower. There is no scope for validation in innerHTML. Therefore, it is easier to insert rogue code in the document and make the web page unstable. Modify or remove a CSS style from an element by using the style property. It works similarly to applying a style with the inline style attribute. document.querySelector(h2.style.color="green"); 8 Adding and Removing Elements Create a new element: el=document.createElement(HtmlTagName) -> it remains floating in the JavaScript until we add it to the document. li=document.createElement("li"); li.innerHTML=“New element"; Adding nodes: To the parent node: parent.appendChild(childNode); ul=document.querySelector("ul"); ul.appendChild(li); To insert an element before another element: parentNode.insertBefore(InsertedNode, Node2); To replace one node with another one: parentNode.replaceChild(new child, the replaced node); To remove a node (not only elements) or an entire branch from the document tree: parent.removeChild( Node to be removed); DOM Events & Event Flow Events are actions performed either by the user or by the browser. Event handler (event listener) - a function that is called in response to an event. Event handlers have names beginning with "on", DOM Event Flow has three phases: the event capturing phase - provides the opportunity to intercept events, at the target, the event bubbling phase - allows a final response to the event. DOM Events Accessing source element– this Event parameters –event object General: target, type, preventDefault() Keyboard: key, keyCode, altKey, ctrlKey, shiftKey Mouse: pageX, pageY, button, altKey, ctrlKey, shiftKey Events: General: load (window), DOMContentLoaded (document) Keyboard: keydown, keypress, keyup Mouse: mouseenter, mouseleave, mousemove, mouseup, mousedown, click, dblclick DOM Event Handlers Assigning event handlers can be accomplished in a number of different ways: By HTML Event Handlers: assigned using an HTML attribute with the name of the event handler … Example: Function Using Node Properties: to assign a function to an event handler property btn = document.getElementById("myBtn"); btn.onclick = function() { console.log("Clicked");}; By Event Handlers: addEventListener() and removeEventListener()-> multiple event handlers can be added. Arguments: - the event name to handle, - the event handler function, and - a Boolean value indicating whether to call the event handler during the capture phase (true) or during the bubble phase (false). document.getElementById(“test”).addEventListener("click", function() {console.log(“The message”);}); Event handlers added via addEventListener() can be removed only by using removeEventListener() and passing in the same arguments as were used when the handler was added: element.removeEventListener(type,function); Intrinsic Events in Web App Scripts may be assigned to a number of elements through intrinsic event attributes, onload onclick onmouseover onfocus onkeyup onsubmit onselect And so on... Motivation HTML & CSS only allow for static web content, HTML & CSS do not allow for dynamic web content, that can change based on user input activity Web browsers have an engine for generating dynamic content using JavaScript What can be done with JavaScript? To interact with the HTML and CSS content of a document, respond to events. To run in browser methods and functions from the standard JavaScript APIs – defined in W3C standard. To use numerous APIs in addition to the DOM and selector APIs: multimedia, drawing, animating, geolocation, webcam, etc. To work with remote data from a remote HTTP Web server. Deploying JavaScript in HTML Include in HTML file, like: External script: element; src attribute points to an external.js file -> could be located on a web server Embedded script: section ->embedded in HTML Chrome bowser includes “REPL (read evaluate print loop)” console for evaluating JS code Run.js file in a runtime environment, such as Node.js Use tag to handle situations when scripts have been disabled or a certain browser does not support them. JavaScript – Overview & Definitions Derived from ECMAScript standard Originally designated to run on Netscape Navigator Not related to Java JavaScript interpreter embedded in web browsers: Add dynamic behaviour to static web content Scripts can run: When an HTML document loads Accompany form to process input as it is entered Can be triggered by events that affect a document To dynamically create multimedia resources. JavaScript types can be divided into two categories: primitive types and object types. JavaScript Primitive types Number: 5, 1.24, 1.1e5, +Infinity (10308 ), – Infinity (10−324 ), NaN (Number(‘abc’) returns NaN)-> stored using floating-point notation String ‘Hello’ Boolean: true, false Null: null Undefined: undefined boolean, if, delete, var, function, etc. = reserved words of the JavaScript language. There are no behaviour or methods associated with primitive data types. Some primitive data types have wrapper objects. JavaScript Variables & Constants The first letter of a variable can only be "$", "_", "a" to "z", or "A" to "Z" count = 42; // A variable can be a number or a string or a boolean. valleyQuote = “the text” precision = 0.42; condition = true; const DEN_MAX = 5; Variable has two scopes: 1) a global, and 2) block scope. Var keyword is used to declare a local variable or object. If the var keyword is omitted, a global variable is declared. typeof operator - useful for knowing the type of a variable depending in its value. The keyword new is used to create instances of wrapper objects. JavaScript Strings JS strings are series of 16-bit unsigned integers, each integer representing a character. ‘I am a teacher’ vs “I’m a teacher” Escape characters use backslash: ‘\n \t \\’ JS strings are immutable=>any manipulation results in a new string phoneNumber = "(040) 745-789044"; name = “Ion Popescu"; // is the same as: name = 'Ion Popescu'; firstName = ‘Ion'; lastName = ‘Popescu'; firstName + ' ' + lastName; // 'Ion Popescu‘ fullname=firstName.concat(‘ ‘, lastName); String Methods opinion = 'Beyonce is not the best singer in the world'; // searches for 'is', returns its position or -1 if not found isIndex = opinion.indexOf('is'); // returns 8 // extract substring from 0 (inclusive) to isIndex (exclusive) part1 = opinion.substring(0, isIndex); // "Beyonce is" part2 = opinion.substring(14); // "the best singer in the world" fact = part1 + part2; // And now we are good. JavaScript Booleans Any value can be used as a Boolean in JS (when used with logical operators): Falsy values: null, undefined, 0, NaN, ‘’’ Truthy vaues: ‘true’, 6… JavaScript Null & Undefined Null- a value that can be assigned to variables to represent “no value” occupation=null; occupation; //null Undefined – the variable was declared but no value has been assigned salary; salary; //undefined An integer starting with 0 (zero) is considered in JavaScript an octal value. Arrays Declaration of an array can use: An array literal – create the array and initialize the elements numbers = [1, 2, 3]; moreNumbers = ["four", "five", "six", "seven"]; mya =[‘car’, 14, false]; //value can be of any type an array constructor – new keyword numArray= new array(1,2,3); numbers; // 1 numbers.length; // 3 numbers; //undefined // adds 4 to the end of the array numbers.push(4); // returns new length, 4 numbers.pop(); // removes 4 and returns it Arrays are JavaScript objects! Array Indices Use a zero-based indexing scheme. Grow or shrink dynamically by adding and removing elements => length property = the largest integer index in the array. When witting an array value by its index arrayVar[index] will: Add an element at that index if index>=arrayVar.length Create a mapping from the index to the element if index properties contain information about error: Message – a descriptive message Name – type of error: TypeError, RangeError, URIError… Custom error objects can be created: throw new Error(“Only positive values are permitted”); Conditionals and Loops if (condition) { // do something } else {//something else } 5first of all JS tries to convert string to numbers 5 affect the current working instance only -> without affecting the static object prototype. To add a new function to the template for the object –modify the prototype of the object. Debuging JavaScript Write messages to the devtool console of your browser Inside the web page –using addXToThePage() function Asynchronous JavaScript (1) JavaScript programs in a web browser are typically event-driven. JavaScript-based servers typically wait for client requests to arrive over the network before they do anything. There are no features of the core language that are themselves asynchronous BUT JavaScript provides powerful features for working with asynchronous code: promises, async, await, and for/await. Asynchronous JavaScript – Common Methods The duality between synchronous and asynchronous behavior is a fundamental concept in a single-threaded event loop model such as JavaScript. I. Using Callbacks II. Using Promises III. Using async and await IV. Using asynchronous Iteration I. Asynchronous Programming with Callback It is derived from a programming paradigm known as functional programming. It is very used to add interactivity in HTML documents. Callback functions in JavaScript: a function passed to another function, and executed inside the function we called. That other function then invokes (“calls back”) your function when some condition is met or some (asynchronous) event occurs. The callback function: notifies you of the condition or event, may include arguments that provide additional details. Common forms of callback-based asynchronous programming: 1. Events - Event-driven JavaScript programs register callback functions for specified types of events in specified contexts. 2. Timers 3. Network events - JavaScript running in the browser can fetch data from a web server. XMLHttpRequest class Events Client-side JavaScript is almost universally event driven=>rather than running some kind of predetermined computation, they typically wait for the user to do something and then respond to the user’s actions. The web browser generates an event when the user presses a key on the keyboard, moves the mouse, clicks a mouse button, or touches a touchscreen device. Event-driven JavaScript programs register callback functions for specified types of events in specified contexts, and the web browser invokes those functions whenever the specified events occur. Callback functions are called event handlers or event listeners, and they are registered with addEventListener():