This document is a table of contents for a book on JavaScript in Depth. It outlines topics that will be covered, including JavaScript syntax, data types, objects, the DOM, and events. The book will discuss built-in objects like Boolean, Number, Array, String, Date, and more. It will explain how to query, traverse, and manipulate the DOM. Finally, it will cover common DOM events like click, mouseover, and key events.
This document is a table of contents for a book on JavaScript in Depth. It outlines topics that will be covered, including JavaScript syntax, data types, objects, the DOM, and events. The book will discuss built-in objects like Boolean, Number, Array, String, Date, and more. It will explain how to query, traverse, and manipulate the DOM. Finally, it will cover common DOM events like click, mouseover, and key events.
This document is a table of contents for a book on JavaScript in Depth. It outlines topics that will be covered, including JavaScript syntax, data types, objects, the DOM, and events. The book will discuss built-in objects like Boolean, Number, Array, String, Date, and more. It will explain how to query, traverse, and manipulate the DOM. Finally, it will cover common DOM events like click, mouseover, and key events.
This document is a table of contents for a book on JavaScript in Depth. It outlines topics that will be covered, including JavaScript syntax, data types, objects, the DOM, and events. The book will discuss built-in objects like Boolean, Number, Array, String, Date, and more. It will explain how to query, traverse, and manipulate the DOM. Finally, it will cover common DOM events like click, mouseover, and key events.
Download as PPTX, PDF, TXT or read online from Scribd
Download as pptx, pdf, or txt
You are on page 1of 48
JavaScript in Depth
Trn Anh Tun
Edit from Telerik Software Academy
tatuanb@gmail.com Table of Contents What we know so far JavaScript syntax JavaScript operators JavaScript Data Types JavaScript Pop-up boxes If and switch, loops functions
What is an object?
2 Table of Contents (2) Built-in JavaScript objects (common) Boolean Number Array String Date RegExp Function Object 3 Table of Contents (3) Built-in JavaScript objects (uncommon) Typed arrays Errors JSON Math Infinity NaN undefined 4 Table of Contents (4) Enter the DOM Difference between JS and DOM DOM objects Querying the DOM Traversing the DOM Manipulation Events 5 What we know so far? Just a recap Built-in Object a.k.a. language features Boolean Boolean Its either true or false There isnt much to it Just know that:
Use x = Boolean(false), or x = false instead 8 x = new Boolean(false) if (x) { // this code will execute } Number Doesnt do much either 9 Array One of the favorite data structures in JS Supports instance and literal syntax Array properties length thats it Array methods Mutators: pop, push, reverse, shift, sort, splice, unshift Accessors: concat, join, slice, indexOf*, lastIndexOf* Iterators*: filter, forEach, every, map, some, reduce
* = not yet fully supported 10 Array Mutators 11 var arr = [1,2,3];
// str.substr(start[, length]) str.substr(0,4) // => Hell // str.substring(indexA[, indexB]) str.substring(0,4) // => Hell Date Creates Date instances which let you work with dates and times. Only instance syntax Few static methods Many instance methods
15 RegExp Deals with regular expression Supports literal and instance syntax RegExp properties global ignoreCase multiline lastIndex RegExp methods exec test 16 Function The function is an object too In case you wander: new Function ([arg1[, arg2[, ... argN]],] functionBody); new Function("a", "b", "return a + b"); Function methods (of note) apply bind call toSource, toString 17 Function Methods 18 function doStuff(a,b,c) { alert(this); alert(a + b + c); }
// function.apply(thisArg[, argsArray]) doStuff.apply(Ola,[2,3,4]) // => Ola, 9 Object Surprisingly, it had few things Now its getting better Methods*: Object creation: create Object properties: hasOwnProperty, definePoperty, defineProperties, keys Sealing seal, freeze, isSealed, isFrozen 19 Document Object Model (DOM) Document Object Model (DOM) Every HTML element is accessible via the JavaScript DOM API Most DOM objects can be manipulated by the programmer The event model lets a document to react when the user does something on the page Advantages Create interactive pages Updates the objects of a page without reloading it 21 DOM Nodes The DOM hierarchy consists of nodes Each node has a type Important types: Node.ELEMENT_NODE == 1 Node.TEXT_NODE == 3 Node.COMMENT_NODE == 8 Node.DOCUMENT_NODE == 9
22 DOM Nodes Types Other types: Node.ATTRIBUTE_NODE == 2 Node.CDATA_SECTION_NODE == 4 Node.ENTITY_REFERENCE_NODE == 5 Node.ENTITY_NODE == 6 Node.PROCESSING_INSTRUCTION_NODE == 7 Node.DOCUMENT_TYPE_NODE == 10 Node.DOCUMENT_FRAGMENT_NODE == 11 Node.NOTATION_NODE == 12 23 Querying the DOM Three general approaches: Query a specific element Query a collection of elements Built in collections Some methods are applied to document only Some could be applied to elements 24 Querying the DOM (2) 25 var header = document.getElementById( header ); // => DOMElement or Null if not found
var inputs = document.getElementsByName( choises ); // => NodeList with 0 or more elements
var divs = document.getElementsByTagName( div ); // => NodeList with 0 or more elements
var popups = document.getElementsByClassName( popup ); // => NodeList with 0 or more elements
var links = document.links; // => NodeList with 0 or more elements
var header1 = document.querySelector( #header ); var popups2 = document.querySelectorAll( .popup ); Querying the DOM (3) 26 var section = document.getElementById( section );
var divs = section.getElementsByTagName( div );
var popups = section.getElementsByClassName( popup );
var header = section.querySelector( #header ); var popups2 = section.querySelectorAll( .popup ); Some methods are applied to document only Some could be applied to elements Traversing the DOM 27 You are somewhere in the DOM and you need to get elsewhere Methods for adjacent nodes Methods for children collection Traversing the DOM (2) 28 // Going UP node.parentNode // parent node or null if node is document
// Going DOWN node.childNodes // collection of all the child nodes node.fistChild // first node or null if none node.lastChild // last node or null if none
// Going LEFT node.previousSibling // preceding node or null if none
// Going RIGHT node.nextSibling // succeeding node or null if none Accessing Elements through the DOM Tree Example Warning: may not return what you expected due to Browser differences 29 var el = document.getElementById('div_tag'); alert (el.childNodes[0].value); alert (el.childNodes[1]. getElementsByTagName('span').id);
<div id="div_tag"> <input type="text" value="test text" /> <div> <span id="test">test span</span> </div> </div> accessing-elements-demo.html DOM Manipulation Once we access an element, we can read and write its attributes
30 function change(state) { var lampImg = document.getElementById("lamp"); lampImg.src = "lamp_" + state + ".png"; var statusDiv = document.getElementById("statusDiv"); statusDiv.innerHTML = "The lamp is " + state"; }
<img src="test_on.gif" onmouseover="change('off')" onmouseout="change('on')" /> DOM-manipulation.html Common Element Properties Most of the properties are derived from the HTML attributes of the tag E.g. id, name, href, alt, title, src, etc style property allows modifying the CSS styles of the element Corresponds to the inline style of the element Not the properties derived from embedded or external CSS rules Example: style.width, style.marginTop, style.backgroundImage 31 Common Element Properties (2) className the class attribute of the tag innerHTML holds all the entire HTML code inside the element Read-only properties with information for the current element and its state tagName, offsetWidth, offsetHeight, scrollHeight, scrollTop, nodeType, etc 32 DOM Events DOM Events JavaScript can register event handlers Events are fired by the Browser and are sent to the specified JavaScript event handler function Can be set with HTML attributes (legacy):
Can be accessed through the DOM (legacy): 34 <img src="test.gif" onclick="imageClicked()" /> var img = document.getElementById("myImage"); img.onclick = imageClicked; DOM Events (2) Can be accessed through the DOM (standard):
onclick vs click Clicking on one element, clicks all the way up the DOM! False makes element event to fire first 35 var img = document.getElementById("myImage"); img.addEventListiner(click, imageClicked, false) The HTML DOM Event Model (3) All event handlers receive one parameter It brings information about the event Contains the type of the event (mouse click, key press, etc.) Data about the location where the event has been fired (e.g. mouse coordinates) Holds a reference to the event sender E.g. the button that was clicked 36 The HTML DOM Event Model (4) Holds information about the state of [Alt], [Ctrl] and [Shift] keys Some browsers do not send this object, but place it in the document.event Some of the names of the events object properties are browser-specific 37 Common DOM Events Mouse events: onclick, onmousedown, onmouseup onmouseover, onmouseout, onmousemove Key events: onkeypress, onkeydown, onkeyup Only for input fields Interface events: onblur, onfocus onscroll 38 Common DOM Events (2) Form events onchange for input fields onsubmit Allows you to cancel a form submission Useful for form validation Miscellaneous events onload, onunload Allowed only for the <body> element Fires when all content on the page was loaded / unloaded 39 onload Event Example onload event
40 <html> <head> <script type="text/javascript"> function greet() {alert("Loaded.");} document.body.addEventListener(load, greet, false) </script> </head> <body> </body> </html> Debugging JavaScript Debugging JavaScript Modern browsers have JavaScript console where errors in scripts are reported Errors may differ across browsers Several tools to debug JavaScript Microsoft Script Editor Add-on for Internet Explorer Supports breakpoints, watches JavaScript statement debugger; opens the script editor 42 Firebug Firebug Firefox add-on for debugging JavaScript, CSS, HTML Supports breakpoints, watches, JavaScript console editor Very useful for CSS and HTML too You can edit all the document real-time: CSS, HTML, etc Shows how CSS rules apply to element Shows Ajax requests and responses Firebug is written mostly in JavaScript 43 Firebug (2) 44 JavaScript Console Object The console object exists only if there is a debugging tool that supports it Used to write log messages at runtime Methods of the console object: debug(message) info(message) log(message) warn(message) error(message) 45 Browser differences Every browser for itself Browser differences The landscape today: Desktop 5 major desktop browsers 4 major desktop rendering engines Mobile 4 major mobile browsers 4 major mobile rendering engines Platform = browser + OS Make the math