Your SlideShare is downloading. ×
0
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Art of Javascript
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Art of Javascript

905

Published on

Basic JavaScript …

Basic JavaScript
Object Oriented
Best Practices
Library
MVC
Performance
Debug
Documentation
Tools

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
905
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
6
Comments
0
Likes
0
Embeds 0
No embeds

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
  • http://stackoverflow.com/questions/12823264/get-all-elements-in-the-body-tag-using-pure-javascript
  • Jquery:http://jqueryui.com/demos/The Dojo Toolkit:http://demos.dojotoolkit.org/demos/The Yahoo! User Interface Library:Prototype (and Script.aculo.us):MooToolshttp://mootools.net/demos/Ext JS:http://www.sencha.com/products/extjs/examples/http://docs.sencha.com/extjs/4.2.1/extjs-build/examples/sandbox/sandbox.html
  • Jquery:http://jqueryui.com/demos/The Dojo Toolkit:http://demos.dojotoolkit.org/demos/The Yahoo! User Interface Library:Prototype (and Script.aculo.us):MooToolshttp://mootools.net/demos/Ext JS:http://www.sencha.com/products/extjs/examples/http://docs.sencha.com/extjs/4.2.1/extjs-build/examples/sandbox/sandbox.html
  • http://ocanvas.org/demos
  • Demo:http://learn.knockoutjs.com/#/?tutorial=introhttp://knockoutjs.com/documentation/browser-support.html
  • Transcript

    • 1. JavaScript is a lightweight programming language to add interactivity to HTML pages.
    • 2.  Put dynamic text into an HTML page.  React to events  Read and write HTML elements  Validate input data  Detect the visitor's browser  Create cookies
    • 3. New in Html 5:  Access new HTML Elements and Events.  Draw using canvas object  Geolocation: get current location position.  Offline Storage  Post message  Multiple Thread  Socket Programming  Offline web application
    • 4.  Embedded in Html. <script type="text/javascript"><![CDATA[ JavaScript Code ]]></script>  Scripts can be provided locally or remotely. <script language="JavaScript” type="text/javascript“ src="http://somesite/myOwnJavaScript.js"> </script>
    • 5.  Variable scope and declaration.  Popup Boxes: alert("sometext") confirm("sometext") prompt("sometext","defaultvalue")
    • 6.  Conditional statement • if, if.. else, switch  Loop • for loop, while loop  try...catch  Throw  Encapsulate your code into functions
    • 7.  Common Features • DOM Selector • DOM modification • Traversing • Dynamic Styles • Events
    • 8. Compatibility Items:  Elements  Attributes  Browser version  Device/Operating system Detect the visitor's browser var x = "User-agent header sent: " + navigator.userAgent; User-agent header sent: Opera/9.80 (Windows NT 5.1) Presto/2.12.388 Version/12.16
    • 9. var el = document.createElement(“new_el”); element.appendChild(el); document.body.appendChild(el);
    • 10. var fragment = document.createDocumentFragment (); fragment.appendChild(el_1) fragment.appendChild(el_2) fragment.appendChild(el_3) fragment.appendChild(el_4) document.body.appendChild(fragment);
    • 11. var el = document.getElementById(„Id‟);//single element if (document.all || document.getElementById) { ... } val el = document.get ElementsByClassName(„el‟);//select collection of nodes el[0] //get the first element val el = document.get ElementsByTagName(„tagName‟);//select collection of nodes el[0] //get the first element val el = document.get ElementsByTagName(„*‟);//select all tags val el = document.get ElementsByName(„el‟);//select collection of nodes el[0] //get the first element
    • 12. var el = document.querySelector(„#Id‟);//select first element val el = document.querySelector( „.el‟);//select first element val el = document.querySelectorAll( „.el‟);//select collection of nodes
    • 13.  Some old: • getElementById • getElementsByTagNameNot work with object  Some new: • getElementsByClassName  Firefox 3, Safari 3, Opera 9.6, IE9  Opera doesn’t match a second-specified class • querySelectorAll  In Firefox 3.1, Safari 3.1, Opera 10, IE 8  Safari 3.1 had memory out of bounds problems  Safari 3.2 can’t match uppercase characters in quirks mode
    • 14. DOM Collection links document.links document.links[0] forms document.forms document.forms[0] anchors document.anhors document. anhors[0]
    • 15. element.innerHTML = “HTML code”; var attributeValue = element.getAttribute(attributeName); element.setAttribute(attributeName, attributeValue);
    • 16. element.removeChild(el1);
    • 17. var el = element.parentNode; var el = element.childNodes; //Elements + White space var el = element.children; //Only Elements var el = element..nextSibling; //next node or null var el = element..previousSibling; //previous node or null var el = element..nextElementSibling; var el = element..previousElementSibling;
    • 18.  onabort - Loading of an image is interrupted  onblur - An element loses focus  onchange - The content of a field changes  onclick - Mouse clicks an object  ondblclick - Mouse double-clicks an object  onerror - An error occurs when loading a document or an image  onfocus - An element gets focus  onkeydown - A keyboard key is pressed
    • 19.  onkeypress - A keyboard key is pressed or held down  onkeyup - A keyboard key is released  onload - A page or an image is finished loading  onmousedown - A mouse button is pressed  onmousemove - The mouse is moved  onmouseout - The mouse is moved off an element  onmouseover - The mouse is moved over an element  onmouseup - A mouse button is released
    • 20.  onreset - The reset button is clicked  onresize A window or frame is resized  onselect - Text is selected  onsubmit - The submit button is clicked  onunload - The user exits the page
    • 21. <img id="myImage" src="http://3.bp.blogspot.com/_ss1KeGx9Bng/THgWaTaHhuI/AAAAAAAAAB0/3PL mvniAdNk/s1600/lolcats_oh-noes_ihasletgo.jpg"> <script> var img = document.getElementById("myImage"), img2=new Image(), originalSrc = img.src; img2.src="https://i.chzbgr.com/maxW500/6073452544/h4B353A81/"; img.onmouseover = function(){ document.getElementById('myImage').src=img2.src; } img.onmouseout = function(){ document.getElementById('myImage').src=originalSrc; } </script>
    • 22. // Internet Explorer element.attachEvent('click', function() { alert(window.event); } ) // Everyone else element.addEventListener('click', function(ev) { alert(ev) }, false );
    • 23.    Bubbling: the event is first captured and handled by the inner most element and then propagated to outer elements. Capturing : event is first captured by the outer most element and propagated to the inner most element. Only event bubbling model is supported by all the major browsers. if ( <addEventListener detect> ) { // W3C DOM Event Model // Supported by: Firefox, Chrome, Safari, Opera, and (now) IE9 } else if ( <IE or attachEvent detect> ) { // Previous IE Event Model code }
    • 24. To preventing any parent event handlers from being executed. addEvent(div, 'mouseover', function(ev) {event = event || window.event // cross-browser event if (event.stopPropagation) { // W3C standard variant event.stopPropagation() } else { // IE variant event.cancelBubble = true } });
    • 25. JavaScript is an Object Oriented Programming (OOP) language
    • 26.  Primitive Types  Reference Types
    • 27. • Boolean true, false • Number 1, 3.141, -1.602e-19 • String "Joe" • null null • undefined undefined
    • 28.  Only one number type  64 bit floating point  Does not map well to common understanding of arithmetic  0.1 + 0.2 = 0.30000000000000004
    • 29.  Special number: Not a Number  Result of undefined or erroneous operations.  Toxic: any arithmetic operation with NaN will have a NaN as a result.  NaN is not equal anything including NaN
    • 30. Number(value)  Convert the value into a number.  It produces NaN if it has a problem.
    • 31. parseInt(value,10)  Convert the value into a number.  It stops at the first non-digit character.  The radix (10) should be required parseInt(“08”) === 0 parseInt(“08”, 10) === 8
    • 32.          abs absolute value floor integer log logarithm max maximum pow raise to a power random random number round nearest integer sin sin sqrt square root
    • 33.  Unicode  String literals can use single or double quotes.
    • 34.             charAt concat indexOf lastIndexOf match replace search slice split substring toLowerCase toUpperCase
    • 35. A value that isn’t anything
    • 36.  Default value for variables and parameters  The value of missing members in objects function isDefined(value) { return(typeof value != "undefined"); }
    • 37.      Date new Date(1211623944453); Error new Error("Oops!"); RegExp /^web.*$/i; Array [ "apple", "banana" ] Function function(x) {return x*x}
    • 38.  Date new Date() ; //Current date new Date(year, month, day); Date.parse('2/6/2009');//wrong will depend on culture  Y2K Problem Date.prototype.getRealYear = function() { if(this.getFullYear) return this.getFullYear(); else return this.getYear() + 1900; };
    • 39. unordered collection of properties with arbitrary values  object literal var obj = { name: "Joe", age: 26 };  setting a property obj.lastName = "Smith";  retrieving properties alert(obj.name + " " + obj.lastName);
    • 40. Data structure that associates arbitrary values with arbitrary strings  property name as an identifier obj.lastName = "Smith";  property name as a string obj["lastName"] = "Smith";  for( prop in obj ) { alert( prop + ": " + obj[prop] ); }
    • 41. Concept of a class does not exist... ... but use a function as a constructor:  function Dog() {}; class “Dog”  var lassie = new Dog(); instance “lassie”  alert(lassie instanceof Dog); // true
    • 42. Because functions are „first-class objects“ we can attach properties:  Class Variables Dog.SPECIES = "Canis lupus";  Class Methods Dog.getCount = function() { return Dog.COUNT; };
    • 43.  Instance Variables function Dog(name) { this.name = name; }; var lassie = new Dog("Lassie"); alert( lassie.name );
    • 44.  Instance Methods function Dog(name) { this.name = name; this.bark = function() { alert("Woof!") }; }; var lassie = new Dog("Lassie"); lassie.bark();
    • 45.  Global Scope • Variables outside of any functions • Variables inside functions without var var global1 = 1; global2 = 2; function foo() { global3 = 3; };
    • 46.  Function Scope • Variables inside functions declared with var • Function arguments function foo(local1) { var local2 = 2; };
    • 47.  Block Scope ... but can be faked: // before block (function() { // inside block })(); // after block
    • 48. function Dog(name) { var _name = name; // private variable // privileged method this.getName = function() { return _name; }; }; var lassie = new Dog("Lassie"); alert( lassie.getName() );
    • 49. function Dog(name) { var _name = name; // private method var _fixName = function() { return _name.toUpperCase(); }; this.getName = function(){ return _fixName(); }; };
    • 50.  Nested functions  Inner function has still access to local  variables even after the outer function  has finished
    • 51. function outer() { var count = 1; function inner() { alert(count++) } return inner; } var myClosure = outer(); myClosure(); // ==> 1 myClosure(); // ==> 2
    • 52.  function Pet() {}; Pet  function Dog() {};  Dog.prototype = new Pet; Dog
    • 53. function Pet(name) { this.name = name; }; function Dog(name) { // super(name) Pet.call( this, name ); this.bark = function() {}; }; Dog.prototype = new Pet;
    • 54.  // old: attach to "this“ function Dog(name) { this.bark = function(){ alert("Woof!") }; };  // new: attach to "prototype" function Dog(name) {}; Dog.prototype.bark = function(){ alert("Woof!") }; };
    • 55.  Property values on instance:  local, instance-specific values  Property values on prototype:  read-only default values attaching to the prototype saves memory, especially for large numbers of instances
    • 56.  Affects all new instances  Affects all existing instances  Allows modification of existing classes String.prototype.trim = function() { return this.replace(/^s+/, ""); }; alert(" Lassie".trim() );
    • 57. function Dog() {}; Dog.prototype.bark = function() { alert("Woof!") }; function Bulldog() {}; Bulldog.prototype = new Dog; Bulldog.prototype.bark = function() { // super.bark(); Dog.prototype.bark.call(this); alert("Grrrh!!") };
    • 58. function Pet() { if(this._id == Pet._id) { throw new Error("No Pets, please!"); } } Pet._id = "Pet"; Pet.prototype._id = "Pet"; var fiffy = new Pet; // Error (intended)
    • 59. But now our code to setup inheritance will fail: Dog.prototype = new Pet; // Error :-( Solution: Do not create an instance of the actual superclass just to setup inheritance, use a dummy: function Dummy() {}; Dummy.prototype = Pet.prototype; Dog.prototype = new Dummy;
    • 60. if (typeof very == "undefined") { very = {}; } if (typeof very.cute == "undefined") { very.cute = {}; } very.cute.Dog = function() {}; var fiffy = new very.cute.Dog;
    • 61. // The Last of the Mohicans var chingachgook = { fight : function() { alert("Woah!"); } }; chingachgook.fight();
    • 62. function Mohican() { this.fight = function(){alert("Woah!")} }; Mohican.getInstance = function() { if (!this._instance) { this.instance = new this; } return this._instance; }; Mohican.getInstance().fight();
    • 63.  Avoiding Conflicts with Other Libraries ($) <!-- Putting jQuery into no-conflict mode. --> <script src="prototype.js"></script> <script src="jquery.js"></script> <script> var $j = jQuery.noConflict(); // $j is now an alias to the jQuery function; creating the new alias is optional. $j(document).ready(function() { $j( "div" ).hide(); }); // The $ variable now has the prototype meaning, which is a shortcut for // document.getElementById(). mainDiv below is a DOM element, not a jQuery object. window.onload = function() { var mainDiv = $( "main" ); } </script>
    • 64.  use multiple window.onload events with external scripts: window.onload = init; function addOnloadEvent(fnc){ if ( typeof window.addEventListener != "undefined" ) window.addEventListener( "load", fnc, false ); else if ( typeof window.attachEvent != "undefined" ) { window.attachEvent( "onload", fnc ); } else { if ( window.onload != null ) {var oldOnload = window.onload; window.onload = function ( e ) {oldOnload( e ); window[fnc]();}; } else window.onload = fnc; } } addOnloadEvent(myFunctionName);
    • 65.  Feature-Detect Rather Than Browser-Detect if (document.getElementById) { var element = document.getElementById('MyId'); } else { alert('Your browser lacks the capabilities required to run this script!'); }  Use Square Bracket Notation MyObject.property MyObject."value"+I (Work) (not Work) formref.elements.name[] (not Work) MyObject["property"] (Work) MyObject["value"+i] (Work) formref.elements["name[]"] (Work)
    • 66.  Use onclick In Anchors Instead Of javascript: Pseudo-Protocol <a href="/" onClick="return validate();">Home</a> function validate() { return prompt("Are you sure you want to exit this page?"); }  What Not To Do <a href="javascript:doSomething()">link</a> <a href="#" onClick="doSomething()">link</a> <a href="#" onClick="javascript:doSomething();">link</a> <a href="#" onClick="javascript:doSomething(); return false;">link</a>
    • 67.  Use The Unary + Operator To TypeConvert To Number function total() { var theform = document.forms["myform"]; var total = (+theform.elements["val1"].value) + (+theform.elements["val2"].value); alert(total); // This will alert 3 }  Don't Use HTML Comments In Script Blocks <script language="javascript"> <!-// code here //--> </script>
    • 68.  Avoid Cluttering The Global Namespace var MyLib = {}; // global Object cointainer MyLib.value = 1; MyLib.increment = function() { MyLib.value++; } MyLib.show = function() { alert(MyLib.value); } MyLib.value=6; MyLib.increment(); MyLib.show(); // alerts 7
    • 69.     Model: organize the application's data layer. View: Templates to render HTML data in controllers and inject them into the DOM. Composed Views: divide the view into small blocks which can be reused or adapted to different scenarios. Controller : A controller is a list of functions that gets called back when the appropriate event happens.
    • 70.  Extend Methods.  UI Controls and Library.  Compatibility.  Performance.
    • 71.  Jquery  The Dojo Toolkit  The Yahoo! User Interface Library  Prototype (and Script.aculo.us)  MooTools  ExtJS provides everything you need to build robust desktop and mobile web apps.
    • 72.  JavaScriptMVC  Knockout  AngularJS
    • 73. Framework UI Bindings Composed Views Web Presentation Layer Plays Nicely With Others Backbone.js ✗ ✗ ✓ ✓ SproutCore 1.x ✓ ✓ ✗ ✗ Sammy.js ✗ ✗ ✓ ✓ Spine.js ✗ ✗ ✓ ✓ Cappuccino ✓ ✓ ✗ ✗ Knockout.js ✓ ✗ ✓ ✓ Javascript MVC ✗ ✓ ✓ ✓ Google Web Toolkit ✗ ✓ ✗ ✗ Google Closure ✗ ✓ ✓ ✗ Ember.js ✓ ✓ ✓ ✓ Angular.js ✓ ✗ ✓ ✓ Batman.js ✓ ✗ ✓ ✓
    • 74.   Define local variables var doc = document; elem = doc.getElementById(“objId”); Combine control conditions and control variable changes when using loops var x = 9; do { } while( x-- );
    • 75.  Define arrays for HTML collection objects function array(items) { try { return Array.prototype.concat.call(items); } catch (ex) { var i = 0, len = items.length, result = Array(len); while (i < len) { result[i] = items[i];i++; } return result; } } var divs = array( document.getElementsByTagName('div') ); for (var i=0l i < divs.length; i++ ) { var div = document.createElement("div"); document.appendChild(div); }
    • 76.  Appending DOM elements all at once faster than adding them individually.  var div = document.getElementsByTagName("div"); var fragment = document.createDocumentFragment(); for ( var e = 0; e < elems.length; e++ ) { fragment.appendChild( elems[e] ); } for ( var i = 0; i < div.length; i++ ) { div[i].appendChild( fragment.cloneNode(true) ); }  Change CSS classes not styles
    • 77.  Optimizing Events <ul id="menu"> <li id="home">Home</li> <li id="products">Products</li> <li id="portfolio">Portfolio</li> <li id="shop">Shop</li> </ul> var menuHandler = function(event) { event = event || window.event; var target = event.target || event.srcElement; if (target.id === 'home') {// go home} } document.getElementById('menu').addEventListener('cli ck',menuHandler);
    • 78.  Avoid memory leaks and circular references in your closures //Classic case for circular references function foo(e,d) { $(e).on("click", function() { //Do something with d }); } //Break the cycle! function foo(e, d) { $(e).on("click", cbk(d)); } function cbk (d) { }     Avoid using eval Minimize file size Caching use external file Deferred execution
    • 79.  Loading on demand <script src="lab.js"></script> <script> $LAB .script("jquery.js") .wait() .script("jquery.color.js") .script("jquery.otherplugin.js") .script("mylib.js") .wait() .script("unrelated1.js") .script("unrelated2.js"); </script>   Minimize file size (use minified files) Deferred execution
    • 80.  Frame  Eval  Html Encode: • escape • encodeURI • encodeURIComponent • html.replace(/</g,"<").replace(/>/g,">")  Obfuscate using tool YUI Compressor. Will it protect javascript?
    • 81. TOOLS
    • 82.  Firebug (FF)  MS Visual Web Developer (IE)  DragonFly (Opera)  Chrome  Drosera / Web Inspector (Safari)  Console: http://code.google.com/p/console-js/ http://patik.com/blog/complete-cross-browserconsole-log/
    • 83.  Dojo Shrink Safe http://shrinksafe.dojotoolkit.org/  YUI http://refresh-sf.com/yui/  Dean Edwards Packer / Compress.js
    • 84.  Yslow  Firebug  Chrome's development tools
    • 85.  In browser (easy) - JSUnit  Browser Control (comprehensive) – Selenium http://www.seleniumhq.org/  Simulated (fast) – Env.js http://www.envjs.com/
    • 86. – Understands JavaScript, hard to document complex features http://code.google.com/p/jsdoc-toolkit/  Natural Docs – Can document anything  MVCDoc – Can document anything, understands some JS.  JSDoc

    ×