JavaScript Basics And DOM Manipulation

Loading...

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

0 comments

Post a comment

    Post a comment
    Embed Video
    Edit your comment Cancel

    7 Favorites

    JavaScript Basics And DOM Manipulation - Presentation 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); >> \"number\" var n2 = 1.5; out(typeof n2); >> \"number\" var n3 = 0100; out(typeof n3); >> \"number\" out (n3); >> 64 var n4 = 0xFF; out(typeof n4); >> \"number\" out(n4); >> 255
    9. JavaScript: Primitive types: Numbers var n5 = 1e1; out(typeof n5); >> \"number\" out(n5); >> 10 var n6 = 2e+3; out(typeof n6); >> \"number\" out(n6); >> 2000 var n7 = 2e-3; out(typeof n7); >> \"number\" out(n7); >> 0.002
    10. JavaScript: Primitive types: Numbers var n8 = Infinity; out(typeof n8); >> \"number\" out(n8); >> Infinity var n9 = 1e309; out(typeof n9); >> \"number\" out(n9); >> Infinity var n10 = 6/0; out(typeof n10); >> \"number\" out(n10); >> Infinity var n11 = -1*Infinity; out(typeof n11); >> \"number\" out(n11); >> -Infinity
    11. JavaScript: Primitive types: Numbers var n12 = NaN; out(typeof n12); >> \"number\" out(n12); >> NaN var n13 = 10 * \"string\"; out(typeof n13); >> \"number\" out(n13); >> NaN var n14 = 1 + 1 + NaN; out(typeof n14); >> \"number\" out(n14); >> NaN { } NaN - Not a Number.
    12. Strings
    13. JavaScript: Primitive types: Strings var s1 = \"some string\"; out(typeof s1); >> \"string\" var s2 = 'a'; out(typeof s2); >> \"string\" var s3 = \"10\"; out(typeof s3); >> \"string\" { } Any value placed between single or double quotes is considered a string.
    14. JavaScript: Primitive types: String var s41 = \"one\"; var s42 = \"two\" var s43 = s41 + s42; out(s43); >> \"onetwo\" var s51 = \"10\"; out(typeof s51); >> \"string\" var s52 = s51 * 5; out(s52); >> 50 out(typeof s52); >> \"number\" var s6 = \"1\"; out(typeof s6); >> \"string\" out(++s6); >> 2 out(typeof s6); >> \"number\" var s7 = \"some string 1\"; var s71 = s7 * 1; out(typeof s7); >> \"string\" out(s71); >> NaN out(typeof s71); >> \"number\"
    15. Boolean
    16. JavaScript: Primitive types: Boolean var b1 = false; out(typeof b1); >> \"boolean\" var b2 = \"some string\"; var b21 = !b2; var b22 = !!b2; out(typeof b2); >> \"string\" out(b21); >> false out(typeof b21); >> \"boolean\" out(b22); >> true out(typeof b22); >> \"boolean\"
    17. JavaScript: Primitive types: Boolean All values become true when converted to a boolean, with the exception of the six falsy values: var b31 = \"\"; } 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!=\"2\"; >> false var b41 = 2==\"2\"; >> true var b42 = 2!==\"2\"; >> true var b43 = 2===\"2\"; >> false
    20. Null & Undefined
    21. JavaScript: Primitive types: Null var nl1 = null; out(typeof nl1); >> \"object\" 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]; >> \"object\" out(typeof a); >> [1,2,3] out(a); >> 1 out(a[0]); >> undefined out(a[5]); a[5] = \"some string\"; a[5] = \"some string\"; >> [1,2,3, undefined, undefined,\"some out(a); string\"] delete a[2]; >> [1,2, undefined, undefined, out(a); undefined, \"some string\"] delete a[5]; >> [1,2, undefined, undefined, out(a); undefined, undefined]
    25. JavaScript: Arrays var a2 = [[1,2,3], [\"string1\",\"string2\",3]]; out(a2[0]); >> [1,2,3] out(a2[1]); >> [\"string1\",\"string2\",3] var a3 = \"one\"; out(typeof a3); >> \"string\" out(a3[0]); >> \"o\" out(typeof a3[0]); >> \"string\" out(a3[1]); >> \"n\"
    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 = \"local\"; if(true) { out(a); >> \"local\" var a2 = \"local-if\"; out(a2); >> \"local-if\" } out(a); >> \"local\" out(a2); >> \"local-if\" }
    32. JavaScript: Functions: Function literal notation Functions are like any other variable. var func3 = function(a,b) { typeof func3 >> \"function\" return a*b; typeof f3 >> \"function\" }; func3(2,2) >> 4 f3(3,3) >> 9 var f3 = func3;
    33. JavaScript: Functions: Built-in constructor var func6 = new Function(\"a,b\",\"return a+b;\"); 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()); >> \"hello, i'm anonymous function!\" } execute(function() { return \"hello, i'm anonymous function!\"; }); (function(a,b) { out(a-b); >> 2 })(5,3);
    35. JavaScript: Functions: Callback Functions function info(){ return \"this is info function.\"; } function execute(func) { out(func()); anonymous callback function } execute(function() { return \"hello, i'm anonymous function!\"; }); callback function execute(info);
    36. JavaScript: Functions: Inner functions •Keep the global namespace clean •Privacy define function function funcTop() { var a = function() { out(\"innerFunction: do some work...\"); } out(\"funcTop: do some work...\"); a(); } call function
    37. JavaScript: Functions: Scope var r5 = \"global\"; var r5 = \"global\"; function func1() { function func1() { out(r5); out(r5); var r5 = \"local\"; } out(r5); } func1(); func1(); r5 >> \"global\" r5 >> undefined r5 >> \"local\"
    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[\"unusual-prop\"] >> \"value\" prop2:\"string\", obj['WTF?$#!@$'].a >> \"a-val\" \"unusual-prop\":\"value\", obj.array >> [1,2,3] 'WTF?$#!@$':{ obj[\"array\"] >> [1,2,3] a:\"a-val\" }, array: [1,2,3] };
    44. JavaScript: Objects : Defining a new property var obj = { prop:1, obj.prop3 >> undefined prop2:\"string\", obj.prop3 = \"value3\"; \"unusual-prop\":\"value\", obj.prop3 >> \"value3\" 'WTF?$#!@$':{ a:\"a-val\" }, array: [1,2,3] };
    45. JavaScript: Objects : Passing Passing objects by reference. var obj1 = { //.. a:\"val-a\" var obj3 = { }; a:\"val-a\" }; var obj2 = obj1; obj1===obj2 >> true obj1.a >> \"val-a\" obj1===obj3 >> false obj2.a >> \"val-a\" obj2.a = \"val-a2\"; obj1.a >> \"val-a2\" obj2.a >> \"val-a2\"
    46. JavaScript: Objects: Functions var dog = { dog.name >> \"Bobik\" name: \"Bobik\", dog.talk() >> \"Woof, woof!\" talk: function() { dog.sayName() >> \"Bobik\" return \"Woof, woof!\"; }, sayName: function() { return this.name; } };
    47. JavaScript: Objects: Constructor function Cat(/*String*/ name) { this.name = name; this.talk = function() { return \"I'm \"+this.name+\". Mrrr, miaow!\"; } } var cat = new Cat(\"Barsik\"); typeof cat >> object cat.name >> \"Barsik\" cat.talk() >> \"I’m Barsik. Mrrr, miaow!\"
    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(\"Barsik\"); typeof cat2 >> undefined cat2.name >> TypeError: cat2 has no properties window.name >> \"Barsik\"
    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(\"Barsik\"); var constr = cat.constructor; var cat3 = cat.constructor(\"Murzik\"); constr >> function Cat(name) { .... } cat3.talk() >> \"I’m Murzik. Mrrr, miaow!\"
    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(\"Barsik\"); //.. var cat4 = {name:\"Chernysh\"}; cat.talk.call(cat4/**, param1, param2, ... **/) >> \"I’m Chernysh. Mrrr, miaow!\" cat.talk.apply(cat4/**, [param1, param2, ...] **/) >> \"I’m Chernysh. Mrrr, miaow!\"
    51. JavaScript: Objects: instanceof operator tests if an object was created with specific constructor instanceof function. var cat = new Cat(\"Barsik\"); 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 \"I'm \"+this.name+\". Mrrr, miaow!\"; } }; the way how enumerate all properties in an object Cat.prototype >> {} (object) for(var i in Cat.prototype) { i+\":\"+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(\"Barsik\"); Cat.prototype.animal = \"cat\"; Cat.prototype >> {animal: \"cat\"} cat.animal >> \"cat\" Cat.prototype.seeADog = function() { return \"I'm \"+this.name+\". Sshhhhhhh!\"; } cat.seeADog() >> \"I'm Barsik. Sshhhhhhh!\";
    57. JavaScript: Prototype: Adding properties The same result as in the previous example ... var cat = new Cat(\"Barsik\"); Overriding the prototype Cat.prototype.animal = \"cat\"; completely Cat.prototype = { animal: \"cat\", seeADog : function() { return \"I'm \"+this.name+\". Sshhhhhhh!\"; } } cat.animal >> \"cat\" cat.seeADog() >> \"I'm Barsik. Sshhhhhhh!\";
    58. JavaScript: Prototype: Changing prototype var cat = new Cat(\"Barsik\"); var cat2 = new Cat(\"Murzik\"); Cat.prototype.animal = \"cat\"; Changing the prototype for all Cat instances cat.animal >> \"cat\" cat2.animal >> \"cat\" Cat.prototype.animal = \"dog\"; cat.animal >> \"dog\" cat2.animal >> \"dog\"
    59. JavaScript: Prototype: Own props vs. prototype ones function Gadget(/*String*/ name) { this.name = name; } var iphone = new Gadget(\"iPhone\"); Gadget.prototype.name = \"none\"; iphone.name >> \"iPhone\" delete iphone.name; iphone.name >> \"none\"
    60. JavaScript: Prototype: Extending built-in objects Yeah, it’s possible... String.prototype.getSecondLetter = function() { return this[1]; } var str = \"hello!\"; str.getSecondLetter() >> \"e\" ... but be careful.
    61. Inheritance
    62. JavaScript: Inheritance: Prototype Chaining Example function Shape() { this.name = \"Shape\"; this.getName = function() { return this.name; } }; function TwoDShape() { this.name = \"2DShape\"; }; function Triangle(/*Number*/ side, /*Number*/ height) { this.side = side; this.height = height; this.name = \"Triangle\"; 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 = \"Hello this world!\"; Obj.prototype.text = \"Hello this world!\"; }; 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 = \"Shape\"; Shape.prototype.getName = function() { return this.name; }; function TwoDShape() {} TwoDShape.prototype = Shape.prototype; TwoDShape.prototype.constructor = TwoDShape; TwoDShape.prototype.name = \"2DShape\"; function Triangle(/*Number*/ side, /*Number*/ height) { this.side = side; this.height = height; } Triangle.prototype = TwoDShape.prototype; Triangle.prototype.constructor = Triangle; Triangle.prototype.name = \"Triangle\"; 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 \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\"> <html> <head> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" /> <title>ToDo list</title> </head> <body> <div>What I need to do.</div> <p title=\"ToDo list\">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=\"text\" id=\"message\" value=\"Messages goes here...\"/> ... var msgInput = document.getElementById(\"message\"); element or null <ul id=\"list\"> <li>Item 1</li> <li>Item 2</li> array of element or an <li>Item 3</li> empty array </ul> ... var items = document.getElementsByTagName(\"li\");
    79. DOM: Elements <p title=\"ToDo list\">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(\"li\"); var text = document.createTextNode(message); item.appendChild(text); parent.appendChild(item); parent.insertBefore(someNode, item); parent.innerHTML = parent.innerHTML + (\"<li>\"+message+\"</li>\"); parent.removeChild(item);
    82. DOM: Event Handlers var addBtn = document.getElementById(\"addBtn\"); var list = document.getElementById(\"list\"); if(addBtn) { addBtn.onclick = function(event) { console.log(event); var value = msgInput.value; if(value) { createListEntry(list,value); } else { alert(\"Message is empty!\"); } } }
    83. DOM: Events: Capturing and Bubbling var addBtn = document.getElementById(\"addBtn\"); //... 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?

    + Siarhei BarysiukSiarhei Barysiuk, 10 months ago

    custom

    2585 views, 7 favs, 2 embeds more stats

    Day 1 of 7-days "JavaScript and Rich User Interface more

    More info about this document

    © All Rights Reserved

    Go to text version

    • Total Views 2585
      • 2562 on SlideShare
      • 23 from embeds
    • Comments 0
    • Favorites 7
    • Downloads 130
    Most viewed embeds
    • 22 views on http://mrthangaraj.blogspot.com
    • 1 views on http://192.168.10.100

    more

    All embeds
    • 22 views on http://mrthangaraj.blogspot.com
    • 1 views on http://192.168.10.100

    less

    Flagged as inappropriate Flag as inappropriate
    Flag as inappropriate

    Select your reason for flagging this presentation as inappropriate. If needed, use the feedback form to let us know more details.

    Cancel
    File a copyright complaint
    Having problems? Go to our helpdesk?

    Categories