JavaScript in Depth
description
Transcript of JavaScript in Depth
![Page 1: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/1.jpg)
JavaScript in Depth
Svetlin NakovTelerik
Corporationwww.telerik.com
![Page 2: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/2.jpg)
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
![Page 3: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/3.jpg)
Table of Contents (2) Built-in JavaScript objects
(common) Boolean Number Array String Date RegExp Function Object
3
![Page 4: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/4.jpg)
Table of Contents (3) Built-in JavaScript objects
(uncommon) Typed arrays Errors JSON Math Infinity NaN undefined
4
![Page 5: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/5.jpg)
Table of Contents (4) Enter the DOM
Difference between JS and DOM DOM objects Querying the DOM Traversing the DOM Manipulation Events
5
![Page 6: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/6.jpg)
Table of Contents (5) Browser differences Feature detection Shims, shivs Polyfills JavaScript libraries Closures Module pattern
6
![Page 7: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/7.jpg)
What we know so far?
Just a recap
![Page 8: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/8.jpg)
Built-in Objecta.k.a. language features
![Page 9: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/9.jpg)
Boolean Boolean It’s either true or false There isn’t much to it Just know that:
Use x = Boolean(false), or x = false instead
9
x = new Boolean(false)if (x) { // this code will execute}
![Page 10: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/10.jpg)
Number Doesn’t do much either
10
![Page 11: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/11.jpg)
Array One of the favourite data structures in
JS Supports instance and literal syntax Array properties
length – that’s 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
11
![Page 12: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/12.jpg)
Array Mutators
12
var arr = [1,2,3];
arr.pop() // => 3 (last element), arr=[1,2]
// Array.push(element)arr.push(4) // => 3 (arr.length), arr=[1,2,4]
arr.reverse() // => [4,2,1], arr=[4,2,1]
arr.shift() // => 4 (first element), arr=[2,1]
// Array.unshift(element)arr.unshift(5) // => 3 (arr.length), arr=[5,2,1]
arr.sort() // => [1,2,5], arr=[1,2,5]
// Array.splice(index, howMany[, element1[,...[,element2]]])arr.splice(1,1,6,7,8) // =>[2] (removed), arr=[1,6,7,8,5]
![Page 13: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/13.jpg)
Array Accessors
13
var arr = [1,2,3];var arr1 = [4,5,6];
arr.concat(arr1) // => [1,2,3,4,5,6], arr=[1,2,3]
// arr.join(separator)arr.join(“ | ”) // => “1 | 2 | 3”, arr=[1,2,3]
// arr.slice(begin[, end])arr.slice(0,1) // => [1,2], arr=[1,2,3]
arr.indexOf(1) // => 0arr.indexOf(5) // => -1
arr.push(1) // arr=[1,2,3,1]arr.lastIndexOf(1) // => 3arr.lastIndexOf(5) // => -1
![Page 14: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/14.jpg)
String For strings or a sequence of characters
(array wise) Supports instance and literal syntax Supports array like accessing e.g.
string[0] String properties
length String methods
charAt, concat, indexOf, lastIndexOf, match, replace, search, slice, split, substr, substring, toUppserCase, toLowerCase, trim*, trimLeft*, trimRight*
Just to name a few14
![Page 15: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/15.jpg)
String Methods
15
var str = “Hello, World!”;
str.charAt(1) // => “e”str.concat(“!!”) // => “Hello, World!!!”
str.indexOf(“o”) // => 4str.indexOf(“x”) // => -1str.lastIndexOf(“o”) // => 8str.lastIndexOf(“x”) // => -1
str.replace(“Hello”, “Goodbye”) // “Goodbye, World!”
str.split(“ ”) // => [“Hello,”, “World!”]
// str.substr(start[, length])str.substr(0,4) // => “Hell”// str.substring(indexA[, indexB])str.substring(0,4) // => “Hell”
![Page 16: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/16.jpg)
Date Creates Date instances which let you work with dates and times.
Only instance syntax Few “static” methods Many instance methods
16
![Page 17: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/17.jpg)
RegExp Deals with regular expression Supports literal and instance syntax RegExp properties
global ignoreCase multiline lastIndex
RegExp methods exec test
17
![Page 18: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/18.jpg)
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
18
![Page 19: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/19.jpg)
Function Methods
19
function doStuff(a,b,c) { alert(this); alert(a + b + c);}
doStuff(1,2,3) // => [Object Window], 6
// function.call(thisArg[, arg1[, … [,argn]]])doStuff.call(“Ola”,2,3,4) // => “Ola”, 9
// function.apply(thisArg[, argsArray])doStuff.apply(“Ola”,[2,3,4]) // => “Ola”, 9
![Page 20: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/20.jpg)
Object Surprisingly, it had few things Now it’s getting better Methods*:
Object creation: create
Object properties: hasOwnProperty, definePoperty,
defineProperties, keys Sealing
seal, freeze, isSealed, isFrozen
20
![Page 21: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/21.jpg)
Document Object Model
(DOM)
![Page 22: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/22.jpg)
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 it22
![Page 23: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/23.jpg)
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
23
![Page 24: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/24.jpg)
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 24
![Page 25: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/25.jpg)
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
25
![Page 26: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/26.jpg)
Querying the DOM (2)
26
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” );
![Page 27: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/27.jpg)
Querying the DOM (3)
27
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
![Page 28: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/28.jpg)
Traversing the DOM
28
You are somewhere in the DOM and you need to get elsewhere
Methods for adjacent nodes Methods for children collection
![Page 29: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/29.jpg)
Traversing the DOM (2)
29
// Going UPnode.parentNode // parent node or null if node is document
// Going DOWNnode.childNodes // collection of all the child nodesnode.fistChild // first node or null if nonenode.lastChild // last node or null if none
// Going LEFTnode.previousSibling // preceding node or null if none
// Going RIGHTnode.nextSibling // succeeding node or null if none
![Page 30: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/30.jpg)
Accessing Elements through the DOM Tree –
Example
Warning: may not return what you expected due to Browser differences 30
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
![Page 31: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/31.jpg)
DOM Manipulation Once we access an element, we can read and write its attributes
31
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
![Page 32: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/32.jpg)
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
32
![Page 33: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/33.jpg)
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…
33
![Page 34: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/34.jpg)
DOM Events
![Page 35: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/35.jpg)
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):
35
<img src="test.gif" onclick="imageClicked()" />
var img = document.getElementById("myImage");img.onclick = imageClicked;
![Page 36: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/36.jpg)
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
36
var img = document.getElementById("myImage");img.addEventListiner(“click”, imageClicked, false)
![Page 37: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/37.jpg)
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
37
![Page 38: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/38.jpg)
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 event’s object properties are browser-specific
38
![Page 39: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/39.jpg)
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 39
![Page 40: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/40.jpg)
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 / unloaded40
![Page 41: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/41.jpg)
onload Event – Example onload event
41
<html><head> <script type="text/javascript"> function greet() {alert("Loaded.");} document.body.addEventListener(“load”, greet, false) </script></head><body></body></html>
![Page 42: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/42.jpg)
Debugging JavaScript
![Page 43: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/43.jpg)
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 43
![Page 44: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/44.jpg)
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
JavaScript44
![Page 45: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/45.jpg)
Firebug (2)
45
![Page 46: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/46.jpg)
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)
46
![Page 47: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/47.jpg)
Browser differences
Every browser for itself
![Page 48: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/48.jpg)
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
48
![Page 49: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/49.jpg)
Feature detection Feature detection Shims, shivs Polyfills JavaScript libraries Clojures Module pattern
49
![Page 50: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/50.jpg)
Shims, shivs What is feature detection Shim – a compatibility
workaround Shiv – a shim that ends with a “v”
50
![Page 51: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/51.jpg)
Polyfills Polyfill, or polyfiller, is a piece of
code (or plugin) that provides the technology that you, the developer, expect the browser to provide natively
Flattening the API landscape if you will
A shim that mimics a future API providing fallback functionality to older browsers
51
![Page 52: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/52.jpg)
Closures A "closure" is an expression
(typically a function) that can have free variables together with an environment that binds those variables (that "closes" the expression)
52
(function() {
// do stuff here // what happens in closure stays in closure // unless exposed
})()
![Page 53: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/53.jpg)
Module pattern Basically, an implementation of
closure
or
53
var Module = (function() { // Do magic stuff here // Don’t forget to return return { … } // some object})()
(function() { // Do magic stuff here // Don’t forget to return window.Module = { … } // some object})()
![Page 54: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/54.jpg)
JavaScript libraries A JS library may:
Abstract common work: Traversing / manipulating DOM Ajax related Animations
Normalize browser differences trough shims
Have syntactic sugar for easier coding
Have a module factory 54
![Page 55: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/55.jpg)
JavaScript in Depth
Questions? ?
?? ? ??
?? ?
?
![Page 56: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/56.jpg)
Exercises1. Create an HTML page that has two text
fields (first name and last name) and a button. When the user clicks the button, a message should show the text in the text fields followed by the current time.
2. Create a Web page that asks the user about his name and says goodbye to him when leaving the page.
3. Modify the previous HTML page to have a text field for email address and on clicking the button check if the email is valid (it should follow the format <something>@<host>.<domain>).
4. Create a Web page that shows 20 <div> elements with random location, size and color.
56
![Page 57: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/57.jpg)
Exercises (2)5. Create a drop-down menu
Use table for the main menu blocks Use hidden <DIV> elements (display: none; position:absolute; top:30px)
Use JavaScript and onmouseover and onmouseout event to change display: none/block
57
![Page 58: JavaScript in Depth](https://reader035.fdocuments.us/reader035/viewer/2022081421/56816460550346895dd63c2e/html5/thumbnails/58.jpg)
Exercises (3)6. Create a DTHML page that has <div>
containing a text that scrolls from right to left automatically Use setInterval() function to move
the text at an interval of 500 ms Use overflow:hidden for the <div> Use scrollLeft and scrollWidth
properties of the <div> element
58