JavaScript Basics And DOM Manipulation
Upcoming SlideShare
Loading in...5
×

Like this? Share it with your network

Share

JavaScript Basics And DOM Manipulation

  • 13,000 views
Uploaded on

Day 1 of 7-days "JavaScript and Rich User Interfaces" training for my colleagues. It's a quintessence of JavaScript Basics.

Day 1 of 7-days "JavaScript and Rich User Interfaces" training for my colleagues. It's a quintessence of JavaScript Basics.

More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
No Downloads

Views

Total Views
13,000
On Slideshare
12,765
From Embeds
235
Number of Embeds
23

Actions

Shares
Downloads
846
Comments
1
Likes
32

Embeds 235

http://mrthangaraj.blogspot.com 75
http://www.slideshare.net 59
http://mrthangaraj.blogspot.in 34
http://www.istudyiwin.com 22
http://www.linkedin.com 16
http://static.slidesharecdn.com 7
http://mrthangaraj.blogspot.be 2
http://shprabin.wordpress.com 2
https://www.linkedin.com 2
https://dist-ed.waketech.edu 2
http://translate.googleusercontent.com 2
http://mrthangaraj.blogspot.co.il 1
http://mrthangaraj.blogspot.fr 1
http://mrthangaraj.blogspot.com.br 1
http://192.168.6.179 1
http://ganeshprabhu-r.blogspot.in 1
http://ganeshprabhu-r.blogspot.com 1
http://mrthangaraj.blogspot.ru 1
http://192.168.10.100 1
http://istudyiwin.com 1
http://rganeshprabhu.blogspot.com 1
http://ctc.blackboard.com 1
http://pmomale-ld1 1

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. JavaScript Basics And DOM Manipulation Siarhei Barysiuk s.barysiuk@sam-solutions.net
  • 2. Our roadmap
  • 3. Important tools to have “Mozilla Firefox is a free and open source web browser descended from the Mozilla Application Suite, managed by the Mozilla Corporation. Firefox had 19.73% of the recorded usage share of web browsers as of August 2008, making it the second-most popular browser in current use worldwide.” www.firefox.com “Firebug integrates with Firefox to put a wealth of web development tools at your fingertips while you browse.You can edit, debug, and monitor CSS, HTML, and JavaScript live in any web page.” www.getfirebug.com “The Aptana Studio Community Edition provides a full-featured web development environment. The Community Edition represents the core pieces of the Aptana frameworks for editing, debugging, synchronization, and project management.” www.aptana.com
  • 4. JavaScript is more than form validation www.go2web20.net • A directory of web 2.0 applications and services • 2670 registered applications
  • 5. JavaScript Primitive Types
  • 6. JavaScript: Primitive types There are five primitive data types in JavaScript: • number • string • boolean • null • undefined Everything that is not a primitive is an object.
  • 7. Numbers
  • 8. JavaScript: Primitive types: Numbers var n1 = 1; out(typeof n1); >> quot;numberquot; var n2 = 1.5; out(typeof n2); >> quot;numberquot; var n3 = 0100; out(typeof n3); >> quot;numberquot; out (n3); >> 64 var n4 = 0xFF; out(typeof n4); >> quot;numberquot; out(n4); >> 255
  • 9. JavaScript: Primitive types: Numbers var n5 = 1e1; out(typeof n5); >> quot;numberquot; out(n5); >> 10 var n6 = 2e+3; out(typeof n6); >> quot;numberquot; out(n6); >> 2000 var n7 = 2e-3; out(typeof n7); >> quot;numberquot; out(n7); >> 0.002
  • 10. JavaScript: Primitive types: Numbers var n8 = Infinity; out(typeof n8); >> quot;numberquot; out(n8); >> Infinity var n9 = 1e309; out(typeof n9); >> quot;numberquot; out(n9); >> Infinity var n10 = 6/0; out(typeof n10); >> quot;numberquot; out(n10); >> Infinity var n11 = -1*Infinity; out(typeof n11); >> quot;numberquot; out(n11); >> -Infinity
  • 11. JavaScript: Primitive types: Numbers var n12 = NaN; out(typeof n12); >> quot;numberquot; out(n12); >> NaN var n13 = 10 * quot;stringquot;; out(typeof n13); >> quot;numberquot; out(n13); >> NaN var n14 = 1 + 1 + NaN; out(typeof n14); >> quot;numberquot; out(n14); >> NaN { } NaN - Not a Number.
  • 12. Strings
  • 13. JavaScript: Primitive types: Strings var s1 = quot;some stringquot;; out(typeof s1); >> quot;stringquot; var s2 = 'a'; out(typeof s2); >> quot;stringquot; var s3 = quot;10quot;; out(typeof s3); >> quot;stringquot; { } Any value placed between single or double quotes is considered a string.
  • 14. JavaScript: Primitive types: String var s41 = quot;onequot;; var s42 = quot;twoquot; var s43 = s41 + s42; out(s43); >> quot;onetwoquot; var s51 = quot;10quot;; out(typeof s51); >> quot;stringquot; var s52 = s51 * 5; out(s52); >> 50 out(typeof s52); >> quot;numberquot; var s6 = quot;1quot;; out(typeof s6); >> quot;stringquot; out(++s6); >> 2 out(typeof s6); >> quot;numberquot; var s7 = quot;some string 1quot;; var s71 = s7 * 1; out(typeof s7); >> quot;stringquot; out(s71); >> NaN out(typeof s71); >> quot;numberquot;
  • 15. Boolean
  • 16. JavaScript: Primitive types: Boolean var b1 = false; out(typeof b1); >> quot;booleanquot; var b2 = quot;some stringquot;; var b21 = !b2; var b22 = !!b2; out(typeof b2); >> quot;stringquot; out(b21); >> false out(typeof b21); >> quot;booleanquot; out(b22); >> true out(typeof b22); >> quot;booleanquot;
  • 17. JavaScript: Primitive types: Boolean All values become true when converted to a boolean, with the exception of the six falsy values: var b31 = quot;quot;; } if ( !b3* ) { var b32 = null; //executes this section var b33 = false; //... var b34 = NaN; } var b35 = undefined; var b36 = 0;
  • 18. JavaScript: Primitive types: Boolean Some interesting comparison operations: != == Equality comparison: Non-equality comparison: Returns true when both operands are Returns true if the operands are equal. The operands are converted to not equal to each other. the same type before being compared. !== === Non-equality comparison without type Equality and type comparison: conversion: Returns true if both operands are Returns true if the operands are not equal and of the same type. equal OR they are different types.
  • 19. JavaScript: Primitive types: Boolean Some interesting comparison operations: var b4 = 2!=quot;2quot;; >> false var b41 = 2==quot;2quot;; >> true var b42 = 2!==quot;2quot;; >> true var b43 = 2===quot;2quot;; >> false
  • 20. Null & Undefined
  • 21. JavaScript: Primitive types: Null var nl1 = null; out(typeof nl1); >> quot;objectquot; out(nl1); >> null var nl2 = 1 + null; out(nl2); >> 1 var nl3 = 1*null; out(nl3); >> 0
  • 22. JavaScript: Primitive types: Undefined var u1 = {}; //try to access to nonexistent //field of the object out(typeof u1.nonexistent); >> undefined out(u1.nonexistent); >> undefined var u2 = 1 + undefined; out(u2); >> NaN var u3 = 1 * undefined; out(u3); >> NaN
  • 23. Arrays
  • 24. JavaScript: Arrays var a = [1,2,3]; >> quot;objectquot; out(typeof a); >> [1,2,3] out(a); >> 1 out(a[0]); >> undefined out(a[5]); a[5] = quot;some stringquot;; a[5] = quot;some stringquot;; >> [1,2,3, undefined, undefined,quot;some out(a); stringquot;] delete a[2]; >> [1,2, undefined, undefined, out(a); undefined, quot;some stringquot;] delete a[5]; >> [1,2, undefined, undefined, out(a); undefined, undefined]
  • 25. JavaScript: Arrays var a2 = [[1,2,3], [quot;string1quot;,quot;string2quot;,3]]; out(a2[0]); >> [1,2,3] out(a2[1]); >> [quot;string1quot;,quot;string2quot;,3] var a3 = quot;onequot;; out(typeof a3); >> quot;stringquot; out(a3[0]); >> quot;oquot; out(typeof a3[0]); >> quot;stringquot; out(a3[1]); >> quot;nquot;
  • 26. Questions?
  • 27. Functions
  • 28. JavaScript: Functions The power of functions. Where most programming languages have a special syntax for some object-oriented features, JavaScript just uses functions. function sum(a,b) { return a + b; } var r1 = sum(1,1); >> 2
  • 29. JavaScript: Functions: Parameters A function may not require any parameters, but if it does and you forget to pass them, JavaScript will assign the value undefined to the ones you skipped. function sum(a,b) { function sum(a,b) { return a + b; return a + b; } } var r2 = sum(1); var r3 = sum(1,2,3,4,5); r2 >> NaN r3 >> 3 { } 1 + undefined = NaN
  • 30. JavaScript: Functions: Parameters is array of parameters which function accepts. arguments function sumAll() { var result = 0; for(var i=0,length=arguments.length;i<length;i++){ result+=arguments[i]; } return result; } var r4 = sum(1,2,3,4,5,6,7); r4 >> 28
  • 31. JavaScript: Functions: Scope Variables in JavaScript are not defined in a block scope, but in a function scope. This means that • if a variable is defined inside a function, it's not visible outside of the function. • if a variable defined inside an if or a for code block is visible outside the code block. function func() { var a = quot;localquot;; if(true) { out(a); >> quot;localquot; var a2 = quot;local-ifquot;; out(a2); >> quot;local-ifquot; } out(a); >> quot;localquot; out(a2); >> quot;local-ifquot; }
  • 32. JavaScript: Functions: Function literal notation Functions are like any other variable. var func3 = function(a,b) { typeof func3 >> quot;functionquot; return a*b; typeof f3 >> quot;functionquot; }; func3(2,2) >> 4 f3(3,3) >> 9 var f3 = func3;
  • 33. JavaScript: Functions: Built-in constructor var func6 = new Function(quot;a,bquot;,quot;return a+b;quot;); func6(2,2) >> 4 { } Do not use the Function() constructor. As with eval() and setTimeout(), always try to stay away from cases where you pass JavaScript code as a string.
  • 34. JavaScript: Functions: Anonymous Functions •You can pass an anonymous function as a parameter to another function. •You can define an anonymous function and execute it right away. function execute(func) { out(func()); >> quot;hello, i'm anonymous function!quot; } execute(function() { return quot;hello, i'm anonymous function!quot;; }); (function(a,b) { out(a-b); >> 2 })(5,3);
  • 35. JavaScript: Functions: Callback Functions function info(){ return quot;this is info function.quot;; } function execute(func) { out(func()); anonymous callback function } execute(function() { return quot;hello, i'm anonymous function!quot;; }); callback function execute(info);
  • 36. JavaScript: Functions: Inner functions •Keep the global namespace clean •Privacy define function function funcTop() { var a = function() { out(quot;innerFunction: do some work...quot;); } out(quot;funcTop: do some work...quot;); a(); } call function
  • 37. JavaScript: Functions: Scope var r5 = quot;globalquot;; var r5 = quot;globalquot;; function func1() { function func1() { out(r5); out(r5); var r5 = quot;localquot;; } out(r5); } func1(); func1(); r5 >> quot;globalquot; r5 >> undefined r5 >> quot;localquot;
  • 38. JavaScript: Functions: Lexical scope In JavaScript, functions have lexical scope. This means that functions create their environment (scope) when they are defined, not when they are executed. function func4() { function func41() { var v = 1; var v = 1; return func5(); }; return (function() { return v; function func5() { })(); return v; }; }; out(func41()); out(func4()); >> ReferenceError: v is not defined >> 1
  • 39. JavaScript: Functions: Lexical scope var a; //.. Global function F() { var b; F //.. b function N() { a var c; Nc //.. } }
  • 40. JavaScript: Functions: Lexical scope var a; var N; Global //.. function F() { F var b; b //.. a N = function () { var c; Nc //.. } }
  • 41. Questions?
  • 42. Objects
  • 43. JavaScript: Objects JavaScript uses •arrays to represent indexed arrays •objects to represent associative arrays (hashes) var obj = { typeof obj >> object prop:1, obj.prop >> obj[quot;unusual-propquot;] >> quot;valuequot; prop2:quot;stringquot;, obj['WTF?$#!@$'].a >> quot;a-valquot; quot;unusual-propquot;:quot;valuequot;, obj.array >> [1,2,3] 'WTF?$#!@$':{ obj[quot;arrayquot;] >> [1,2,3] a:quot;a-valquot; }, array: [1,2,3] };
  • 44. JavaScript: Objects : Defining a new property var obj = { prop:1, obj.prop3 >> undefined prop2:quot;stringquot;, obj.prop3 = quot;value3quot;; quot;unusual-propquot;:quot;valuequot;, obj.prop3 >> quot;value3quot; 'WTF?$#!@$':{ a:quot;a-valquot; }, array: [1,2,3] };
  • 45. JavaScript: Objects : Passing Passing objects by reference. var obj1 = { //.. a:quot;val-aquot; var obj3 = { }; a:quot;val-aquot; }; var obj2 = obj1; obj1===obj2 >> true obj1.a >> quot;val-aquot; obj1===obj3 >> false obj2.a >> quot;val-aquot; obj2.a = quot;val-a2quot;; obj1.a >> quot;val-a2quot; obj2.a >> quot;val-a2quot;
  • 46. JavaScript: Objects: Functions var dog = { dog.name >> quot;Bobikquot; name: quot;Bobikquot;, dog.talk() >> quot;Woof, woof!quot; talk: function() { dog.sayName() >> quot;Bobikquot; return quot;Woof, woof!quot;; }, sayName: function() { return this.name; } };
  • 47. JavaScript: Objects: Constructor function Cat(/*String*/ name) { this.name = name; this.talk = function() { return quot;I'm quot;+this.name+quot;. Mrrr, miaow!quot;; } } var cat = new Cat(quot;Barsikquot;); typeof cat >> object cat.name >> quot;Barsikquot; cat.talk() >> quot;I’m Barsik. Mrrr, miaow!quot;
  • 48. JavaScript: Objects: Constructor function Cat(/*String*/ name) { this refers to the global this.name = name; object window this.talk = function() { //... } } call without new var cat2 = Cat(quot;Barsikquot;); typeof cat2 >> undefined cat2.name >> TypeError: cat2 has no properties window.name >> quot;Barsikquot;
  • 49. JavaScript: Objects: Constructor When an object is created, a special property is assigned to it behind the scenes — the constructor property. var cat = new Cat(quot;Barsikquot;); var constr = cat.constructor; var cat3 = cat.constructor(quot;Murzikquot;); constr >> function Cat(name) { .... } cat3.talk() >> quot;I’m Murzik. Mrrr, miaow!quot;
  • 50. JavaScript: Objects: call and apply Two useful methods of the function objects are call() and apply(). They allow your objects to borrow methods from other objects and invoke them as their own. var cat = new Cat(quot;Barsikquot;); //.. var cat4 = {name:quot;Chernyshquot;}; cat.talk.call(cat4/**, param1, param2, ... **/) >> quot;I’m Chernysh. Mrrr, miaow!quot; cat.talk.apply(cat4/**, [param1, param2, ...] **/) >> quot;I’m Chernysh. Mrrr, miaow!quot;
  • 51. JavaScript: Objects: instanceof operator tests if an object was created with specific constructor instanceof function. var cat = new Cat(quot;Barsikquot;); var o = {}; cat instanceof Cat >> true cat instanceof Object >> true o instanceof Object >> true o instanceof Cat >> false
  • 52. Questions?
  • 53. Prototype
  • 54. JavaScript: Prototype: Intro • not be confusing things, it’s not prototype.js library • JavaScript has prototype-based object model
  • 55. JavaScript: Prototype: prototype property function Cat(/*String*/ name) { this.name = name; this.talk = function() { return quot;I'm quot;+this.name+quot;. Mrrr, miaow!quot;; } }; the way how enumerate all properties in an object Cat.prototype >> {} (object) for(var i in Cat.prototype) { i+quot;:quot;+Cat.prototype[i] >> ${propName}:${propValue} }
  • 56. JavaScript: Prototype: Adding properties Adding methods and properties to the prototype property of the constructor function is another way to add functionality to the objects this constructor produces. var cat = new Cat(quot;Barsikquot;); Cat.prototype.animal = quot;catquot;; Cat.prototype >> {animal: quot;catquot;} cat.animal >> quot;catquot; Cat.prototype.seeADog = function() { return quot;I'm quot;+this.name+quot;. Sshhhhhhh!quot;; } cat.seeADog() >> quot;I'm Barsik. Sshhhhhhh!quot;;
  • 57. JavaScript: Prototype: Adding properties The same result as in the previous example ... var cat = new Cat(quot;Barsikquot;); Overriding the prototype Cat.prototype.animal = quot;catquot;; completely Cat.prototype = { animal: quot;catquot;, seeADog : function() { return quot;I'm quot;+this.name+quot;. Sshhhhhhh!quot;; } } cat.animal >> quot;catquot; cat.seeADog() >> quot;I'm Barsik. Sshhhhhhh!quot;;
  • 58. JavaScript: Prototype: Changing prototype var cat = new Cat(quot;Barsikquot;); var cat2 = new Cat(quot;Murzikquot;); Cat.prototype.animal = quot;catquot;; Changing the prototype for all Cat instances cat.animal >> quot;catquot; cat2.animal >> quot;catquot; Cat.prototype.animal = quot;dogquot;; cat.animal >> quot;dogquot; cat2.animal >> quot;dogquot;
  • 59. JavaScript: Prototype: Own props vs. prototype ones function Gadget(/*String*/ name) { this.name = name; } var iphone = new Gadget(quot;iPhonequot;); Gadget.prototype.name = quot;nonequot;; iphone.name >> quot;iPhonequot; delete iphone.name; iphone.name >> quot;nonequot;
  • 60. JavaScript: Prototype: Extending built-in objects Yeah, it’s possible... String.prototype.getSecondLetter = function() { return this[1]; } var str = quot;hello!quot;; str.getSecondLetter() >> quot;equot; ... but be careful.
  • 61. Inheritance
  • 62. JavaScript: Inheritance: Prototype Chaining Example function Shape() { this.name = quot;Shapequot;; this.getName = function() { return this.name; } }; function TwoDShape() { this.name = quot;2DShapequot;; }; function Triangle(/*Number*/ side, /*Number*/ height) { this.side = side; this.height = height; this.name = quot;Trianglequot;; this.getArea = function() { return this.side * this.height / 2; } }
  • 63. JavaScript: Inheritance: Prototype Chaining Example TwoDShape.prototype = new Shape(); Triangle.prototype = new TwoDShape(); TwoDShape.prototype.constructor = TwoDShape; Triangle.prototype.constructor = Triangle; var t = new Triangle(10,4); >> 20 out(t.getArea()); >> Triangle out(t.getName()); >> function Triangle(side,height){...} out(t.constructor); out(t instanceof Triangle); >> true out(t instanceof TwoDShape); >> true out(t instanceof Shape); >> true out(t instanceof String); >> false out(Triangle.prototype.isPrototypeOf(t)); >> true out(TwoDShape.prototype.isPrototypeOf(t)); >> true out(Shape.prototype.isPrototypeOf(t)); >> true out(String.prototype.isPrototypeOf(t)); >> false var shape = new Shape(); out(shape.getName()); >> Shape
  • 64. JavaScript: Inheritance: Shared Properties Move shared properties to prototype. function Obj() { function Obj() {}; == this.text = quot;Hello this world!quot;; Obj.prototype.text = quot;Hello this world!quot;; }; But how about memory usage?
  • 65. JavaScript: Inheritance: Some profiling results Activity Monitor v. 3.0.1 Mac OS prototype property this. property
  • 66. JavaScript: Inheritance: Inheriting the prototype only function Shape() {} Shape.prototype.name = quot;Shapequot;; Shape.prototype.getName = function() { return this.name; }; function TwoDShape() {} TwoDShape.prototype = Shape.prototype; TwoDShape.prototype.constructor = TwoDShape; TwoDShape.prototype.name = quot;2DShapequot;; function Triangle(/*Number*/ side, /*Number*/ height) { this.side = side; this.height = height; } Triangle.prototype = TwoDShape.prototype; Triangle.prototype.constructor = Triangle; Triangle.prototype.name = quot;Trianglequot;; Triangle.prototype.getArea = function() { return this.side * this.height / 2; }
  • 67. JavaScript: Inheritance: Inheriting the prototype only var t = new Triangle(10,4); >> 20 out(t.getArea()); >> Triangle out(t.getName()); >> function Triangle(side,height){...} out(t.constructor); out(t instanceof Triangle); >> true out(t instanceof TwoDShape); >> true out(t instanceof Shape); >> true out(t instanceof String); >> false out(Triangle.prototype.isPrototypeOf(t)); >> true out(TwoDShape.prototype.isPrototypeOf(t)); >> true out(Shape.prototype.isPrototypeOf(t)); >> true out(String.prototype.isPrototypeOf(t)); >> false var shape = new Shape(); out(shape.getName()); >> Triangle
  • 68. Questions?
  • 69. Even more...
  • 70. JavaScript: General: Even more... • Math - mathematical constants and functions. • Date - working with dates. • RegExp - regular expressions. See more info on www.developer.mozilla.org
  • 71. JavaScript: General: Exception handling try { iDontExist(); } catch(e){ //process error here out(e); >> ReferenceError: iDontExist is not defined } finally { //do some work here }
  • 72. JavaScript: General: Exception handling • EvalError • RangeError • ReferenceError • SyntaxError • TypeError • URIError • Your own with new Error([message[, fileName[, lineNumber]]])
  • 73. Questions?
  • 74. Document Object Model
  • 75. DOM: Introduction The Document Object Model, a language-neutral set of interfaces. The Document Object Model is an API for HTML and XML documents. It provides a structural representation of the document, enabling you to modify its content and visual presentation. Essentially, it connects web pages to scripts or programming languages.
  • 76. DOM: Chair Construction Analogy Model API
  • 77. DOM: HTML document <!DOCTYPE HTML PUBLIC quot;-//W3C//DTD HTML 4.01//ENquot; quot;http://www.w3.org/TR/html4/strict.dtdquot;> <html> <head> <meta http-equiv=quot;Content-Typequot; content=quot;text/html; charset=UTF-8quot; /> <title>ToDo list</title> </head> <body> <div>What I need to do.</div> <p title=quot;ToDo listquot;>My list:</p> <ul> <li>Finish presentation</li> <li>Clean up my home.</li> <li>Buy a bottle of milk. (May be beer will be better?;) </li> </ul> </body> </html>
  • 78. DOM: Finding elements <input type=quot;textquot; id=quot;messagequot; value=quot;Messages goes here...quot;/> ... var msgInput = document.getElementById(quot;messagequot;); element or null <ul id=quot;listquot;> <li>Item 1</li> <li>Item 2</li> array of element or an <li>Item 3</li> empty array </ul> ... var items = document.getElementsByTagName(quot;liquot;);
  • 79. DOM: Elements <p title=quot;ToDo listquot;>My tasks</p> Node types: an HTML element - 1 an attribute - 2 a text node - 3
  • 80. DOM: Element attributes • nodeName • nodeValue • nodeType • parentNode • childNodes • firstChild • lastChild • previousSibling • nextSibling • attributes • ownerDocument
  • 81. DOM: Manipulating the DOM var item = document.createElement(quot;liquot;); var text = document.createTextNode(message); item.appendChild(text); parent.appendChild(item); parent.insertBefore(someNode, item); parent.innerHTML = parent.innerHTML + (quot;<li>quot;+message+quot;</li>quot;); parent.removeChild(item);
  • 82. DOM: Event Handlers var addBtn = document.getElementById(quot;addBtnquot;); var list = document.getElementById(quot;listquot;); if(addBtn) { addBtn.onclick = function(event) { console.log(event); var value = msgInput.value; if(value) { createListEntry(list,value); } else { alert(quot;Message is empty!quot;); } } }
  • 83. DOM: Events: Capturing and Bubbling var addBtn = document.getElementById(quot;addBtnquot;); //... addBtn.addEventListener('click', function(){ //code goes here },false); addBtn.attachEvent('click', function(){ //code goes here });
  • 84. DOM: Events: Capturing and Bubbling
  • 85. DOM: Let’s see an example ToDos application • adding tasks • deleting tasks • reordering tasks • no backend support Very early alpha ;)
  • 86. Questions?