SlideShare ist ein Scribd-Unternehmen logo
1 von 33
Javascript Primer The brainless dump of a brainless man Adam Hepton @ adamhepton 2010-2011, Frogtrade Image by Jeremy Richardson, "Dead Frog" March 25 2006 via Flickr, CC BY-NC-SA 2.0 (http://www.flickr.com/photos/jaded/151806291/)
Arrays and objects [] = array {} = object var arr = []; var oldSchool = array(); var obj = {}; var oldObj = new Object(); var filledArr = [0, 1, "two", 3, "four"]; var fullObj = {    "key" : "value",    "innerArray" :     [3, "more", "things"] }; This is JSON. Valid JSON uses double-quotes. For everything.
Getting content from objects obj.x vs obj[x] obj.x means property 'x' from obj obj[x] means evaluate x, and find the result as a property of obj var obj = {    "name":"Adam",    "age":30 }, fld = 'age'; > obj.name Adam > obj[name] name is not defined > obj.fld fld is not defined > obj[fld] 30
Removing content from objects delete vs splice delete obj[key] array.splice(key, 1) var obj = { "name":"Adam", "age":30 }, arr = [0, 1, 2, 3, 4]; > delete obj['age'] {"name":"Adam"} > obj.splice(0, 1); obj has no method 'splice' > arr.splice(2, 1); [0, 1, 3, 4] > delete arr[1] [0, null, 3, 4] > arr.length 4
Does it exist? typeof Check that something exists before you try and use it, or execution will break. var obj = {    "name":"Adam",    "hoes":[718,202,901,305],    "myFunc": function(i) {      alert(i);    } }; > var x = obj.func(); obj has no method 'func' > typeof obj.func undefined
Verifying type typeof (cont.) var obj = {    "name":"Adam",    "hoes":[718,202,901,305],    "myFunc": function(i) {      alert(i);    } }; > typeof obj; object > typeof obj.myFunc function > typeof obj.hoes object > typeof null object
I am not an object! typeof (cont) > typeof obj === typeof obj.hoes === typeof null; true > obj.hoes [718,202,901,305] > Object.prototype  .toString.call(obj.hoes); [object Array] > obj.member = null; > typeof obj.member object > obj.member && typeof obj.member == 'object' false
Getting info about objects for(var i in obj) To find all the properties of an object, iterate over the object with a for ... in var str = &quot;&quot;; for(var i in obj) {    if(typeof obj[i] == &quot;string&quot;) {      str += obj[i];    } } alert(string); I don't recommend using this on an array, because it is not very efficient - stick with  for(i = 0; i < l; i++)  or, better still,  while(i--)  if you don't care about reverse ordering your array.
Getting MOAR info about objects indexOf To find out whether something exists within an array, use indexOf.  > arr.indexOf(&quot;doesn't exist&quot;) -1 Except in IE, where support for indexOf on arrays in patchy. You could add a simple version to the prototype, but this will affect a for ... in. The safest way is to use a helper function - if you have jQuery to hand, use  $.inArray : if you don't, then roll your own.
Accessing framed content .contentWindow To access the contents of an iframe, use contentWindow, and then continue your call from within that context. You can only manipulate a contentWindow if it is on the same domain (this includes sub-domains). var frameObj =  document.getElementById ('anIframe'); var frameBody = frameObj.contentWindow. document.body; frameBody.innerHTML = &quot;Changed HTML&quot;;
Referencing windows parent.window To do something from within an iframe on the page that contains the iframe, use parent. You can only manipulate a parent window if it is on the same domain (this includes sub-domains). parent.update(a_variable); parent.window.update (a_variable); parent.document.getElement ById('test').innerHTML = 'New Content'; $('#test',parent.document) .html('New Content'); > parent === parent.window true
Scoping Why no usey? Scoping is used to ensure variables are only accessible where they should be. (function() {    var private = 666;    var shh = function() {      alert(private);    };    secHole = function(x) {      private += x;    }; })(); > private private is not defined > shh() shh is not defined > secHole() 666
Revealing Module Pattern Run that by me... var test = function() { var _private = 666; var public = 111; var fn = function() { console.log(_private); }; return { init: fn, p: public }; }(); If it's not in the return, it doesn't exist as far as the rest of the code is concerned Don't forget to execute the function, or you'll feel very foolish
Keep it tight, yo > test.private private is undefined > test.fn fn is undefined > test.public public is undefined > test.init() 666 > test.p 111 var test = function() { var _private = 666; var public = 111; var fn = function() { console.log(_private); }; return { init: fn, p: public }; }();
Evaluation Order Erm, what? var test = function() {    var x = 666;      var fn = function() {      console.log(x);    };    x = 999;    return {init: fn}; }(); > test.init() 999 Because everything is within a function, normal sequential ordering takes place as soon as the function is run for the first time. Good for inits.
Calling within another scope Who gonna .call? Whenever you invoke a function, the this keyword is used to mean &quot;wherever it was called from&quot;, and usually, that means window, or the object where the function sits. You can tell a function to behave as though it was invoked from elsewhere, using .call: window.name = &quot;Thor&quot;; function bleh(i) {    console.log([this.name,     Math.sqrt(i)]); } var me = {&quot;name&quot;:&quot;Adam&quot;}; > bleh(65536); [&quot;Thor&quot;, 256] > bleh.call(me, 256); [&quot;Adam&quot;, 16]
Calling within another scope (II) Read the .map If .call is used for firing one object into a function, .map is its big brother, used to iterate over an array: function foo(bar) {    return Math.pow(bar, 3); } var nums = [0,1,2,3,4]; > foo(5) 125 > var cub = nums.map(foo); [0, 1, 8, 27, 64] > console.log(nums) [0, 1, 2, 3, 4] Note the ordering difference between .call and .map: func.call(obj, param); arr.map(func);
Calling within another scope (III) .reduce() If you wish to perform a function on all members of an array, and get a single result, .reduce is what you want: function foo(a, b) {    return (a * b) - 4; } var nums = [0,1,2,3,4]; > nums.reduce(foo); -164 > foo(0, 1) -4 > foo(-4, 2) -12 > foo(-12, 3) -40 > foo(-40, 4) -164
Calling within another scope (IV) .reduce() more Reduce works by taking the previous value and the current value, but the function can also take the parameters of current index, and the array being worked on itself, should you need them: arr.reduce(    previous_value,    current_value,    [index,    original_array]);
Interlude After the interlude: jQuery http://www.macwhirled.com/bacon.htm
Getting Started $ To start using jQuery, use $. This is an alias to the jQuery object. To perform jQuery once the page and DOM have loaded (properly loaded, not just body onload loaded), use: $(document).ready( ... ); In Frog's PHP, there is a helper function,  html_add_onload , which adds everything within the parameter to a  $(document).ready  function.
Selectors The main use of $ $('div'); // all divs $('#anID'); // an element with an ID of 'anID' $('.frog3'); // all elements with a class of 'frog3' $('div a.special'); // all links with a class of special that have a parent (any depth) div $('div#container > ul.accordion > li'); // All list items that are a child of a UL with class 'accordion', which is a child of a div with class 'container' $('div.post + div.cmmt'); // Find all divs with class 'cmmt' that are next to a div with class 'post'
Psuedo Elements &quot;Suede-o Element: is that something a bit like an element?&quot; - Alistair Gill $('div.post:first'); //or :last $('li.song:even'); $('li.song:gt(3)'); // or :lt(x) $('form#myForm :input'); // all inputs, selects, textareas – anything that can take input  $('div#holder div:visible'); // all visible divs within the holder
Working with Selectors Funsies! $('div.post').each(   function() {    alert($(this).height()); }); Callback function is within the scope of the element itself - as a DOM reference, not a jQuery object $('div.post').hide() .filter('.blog').show(); // find all divs with class 'post', hide them, and if they also have the class 'blog', show them. .filter is a superb method, because you can pass either a selector, or a function in, to get to just the elements you want
Working with Selectors (II) Onesies! $('div.post').has('ul'); // find only posts that have a ul $('div.post').not('ul'); // find only ones that don't $('div.post, div.article, ul.menu').first(); // find the first of any of these selectors $('div#menu') .children('ul:first') .addClass('main').end() .next() .addClass('afterMenu'); // find the div id of menu, then its first child UL. Add a class of main to it, then go back to the menu. Find its next sibling, and add the class of afterMenu to it
Manipulating Selectors Fonzie! $('div.post:first')    .html('<h1>FIRST</h1>' +    $(this).text()); // .html is innerHTML, .text is innerText.  Both getters and setters. if($('input#cName').val()    = frogBlue&quot;) {    $('input#cHex')     .val('#0071b9');    } } // .val is a getter and setter for input fields
Manipulating Selectors (II) Ralph Malph! $('div.post:first')    .addClass('fClass'); $('div.post:last')    .removeClass('post'); $('div.post.eq(2)')    .toggleClass('frogBlue'); var $fP = $('div.post:first'); $fP.append('<h2>END</h2>'); $fP.prepend('<h1>1st</h1>'); $fP.remove('h2'); var $h = $fP.detach('h1'); $h.addClass('first')    .prependTo($fP); var $h2 = $h.clone(); $h2.removeClass('first')    .insertAfter($h);
Traversing Selectors Ron Howard! var $fP =  $('div.post:first'); $fP.next(); // or .prev(), can use a selector $fP.siblings('div.post'); // look in either direction $fP.children('div.commt'); // only one level deep $fP.find('p.commt'); // at any arbitrary depth $fP.parent(); // find the direct parent - can also use a selector $fP.parents('div.cnt'); // at any arbitrary depth upwards $fP.closest('div.hldr'); // iterate upwards, stop when found
Compatibility with DOM jQuery obj v DOM var $fP = $('div.post:first'); // jQuery object var fP = $fP.get(0); // DOM Node  $fP.attr('id') === fP.id;  // finds the ID $fP.id === fP.attr('id');  // error $('div.post').each(    function() { alert(this.id); alert($(this).attr('id')); });
Browser Differences Browser v Feature There are two types of difference between browsers. It's too easy to say, &quot;This is just not working in IE7, so I'll do something for IE7&quot;. More often, it's a feature that's different in one (or two) browsers than another, so you should use feature detection, where possible. $.support gives a nice list of things that are known to be different in certain browsers, so check for that. Also, modernizr.com is helpful, but not used in Frog at the moment. output of $.support for Chrome 12
Optimisation Familiarisation var $divs = $('div'); Store your selectors, if you use them more than once, and they don't change. .each is bad! Closures are bad! $('div').each(function() { $(this).addClass('blue'); }); THE UGLY var addBlue = function() { $(this).addClass('blue'); }; $('div').each(addBlue); THE BAD $('div').addClass('blue'); THE GOOD, THE ONLY
Optimisation (II) Just a nature walk Assigning event handlers to lots of elements is wasteful. Add them to the parent element for FUN TIMES. $('#on div.clk')    .bind('click',     function() { $(this).toggleClass('on'); }); What if we add new ones? What if there are 500 of them? $('#on').bind('click', function(e) { if($(e.target)     .is('div.clk')) {       $(e.target)       .toggleClass('on');     } });
So Long Suckers! I hate you all

Weitere ähnliche Inhalte

Was ist angesagt?

Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, Swift
Yandex
 
Perl.Hacks.On.Vim
Perl.Hacks.On.VimPerl.Hacks.On.Vim
Perl.Hacks.On.Vim
Lin Yo-An
 

Was ist angesagt? (20)

Just-In-Time Compiler in PHP 8
Just-In-Time Compiler in PHP 8Just-In-Time Compiler in PHP 8
Just-In-Time Compiler in PHP 8
 
Short Introduction To "perl -d"
Short Introduction To "perl -d"Short Introduction To "perl -d"
Short Introduction To "perl -d"
 
Data Validation models
Data Validation modelsData Validation models
Data Validation models
 
Let's play a game with blackfire player
Let's play a game with blackfire playerLet's play a game with blackfire player
Let's play a game with blackfire player
 
Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?
 
Swift 2
Swift 2Swift 2
Swift 2
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming Language
 
JSConf: All You Can Leet
JSConf: All You Can LeetJSConf: All You Can Leet
JSConf: All You Can Leet
 
Static Optimization of PHP bytecode (PHPSC 2017)
Static Optimization of PHP bytecode (PHPSC 2017)Static Optimization of PHP bytecode (PHPSC 2017)
Static Optimization of PHP bytecode (PHPSC 2017)
 
Programming Language Swift Overview
Programming Language Swift OverviewProgramming Language Swift Overview
Programming Language Swift Overview
 
Developing iOS apps with Swift
Developing iOS apps with SwiftDeveloping iOS apps with Swift
Developing iOS apps with Swift
 
A Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP GeneratorsA Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP Generators
 
Basics of Java Script (JS)
Basics of Java Script (JS)Basics of Java Script (JS)
Basics of Java Script (JS)
 
PHP Performance Trivia
PHP Performance TriviaPHP Performance Trivia
PHP Performance Trivia
 
Introduction to PHP Lecture 1
Introduction to PHP Lecture 1Introduction to PHP Lecture 1
Introduction to PHP Lecture 1
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation Tutorial
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, Swift
 
Perl.Hacks.On.Vim
Perl.Hacks.On.VimPerl.Hacks.On.Vim
Perl.Hacks.On.Vim
 
Being functional in PHP (DPC 2016)
Being functional in PHP (DPC 2016)Being functional in PHP (DPC 2016)
Being functional in PHP (DPC 2016)
 
The promise of asynchronous PHP
The promise of asynchronous PHPThe promise of asynchronous PHP
The promise of asynchronous PHP
 

Ähnlich wie Javascript Primer

JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
Stoyan Stefanov
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02
Seri Moth
 
Micro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicateMicro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicate
Kiev ALT.NET
 
OO JS for AS3 Devs
OO JS for AS3 DevsOO JS for AS3 Devs
OO JS for AS3 Devs
Jason Hanson
 
Php Reusing Code And Writing Functions
Php Reusing Code And Writing FunctionsPhp Reusing Code And Writing Functions
Php Reusing Code And Writing Functions
mussawir20
 

Ähnlich wie Javascript Primer (20)

Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptBeginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScript
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
JavaScript Needn't Hurt!
JavaScript Needn't Hurt!JavaScript Needn't Hurt!
JavaScript Needn't Hurt!
 
Python - Getting to the Essence - Points.com - Dave Park
Python - Getting to the Essence - Points.com - Dave ParkPython - Getting to the Essence - Points.com - Dave Park
Python - Getting to the Essence - Points.com - Dave Park
 
JavaScript In Object Oriented Way
JavaScript In Object Oriented WayJavaScript In Object Oriented Way
JavaScript In Object Oriented Way
 
JavaScript Literacy
JavaScript LiteracyJavaScript Literacy
JavaScript Literacy
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02
 
JQuery Presentation
JQuery PresentationJQuery Presentation
JQuery Presentation
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
 
Sencha Touch Intro
Sencha Touch IntroSencha Touch Intro
Sencha Touch Intro
 
Ruby For Java Programmers
Ruby For Java ProgrammersRuby For Java Programmers
Ruby For Java Programmers
 
OO in JavaScript
OO in JavaScriptOO in JavaScript
OO in JavaScript
 
Micro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicateMicro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicate
 
Introduction to JQuery
Introduction to JQueryIntroduction to JQuery
Introduction to JQuery
 
OO JS for AS3 Devs
OO JS for AS3 DevsOO JS for AS3 Devs
OO JS for AS3 Devs
 
Java Boilerplate Busters
Java Boilerplate BustersJava Boilerplate Busters
Java Boilerplate Busters
 
And the Greatest of These Is ... Rack Support
And the Greatest of These Is ... Rack SupportAnd the Greatest of These Is ... Rack Support
And the Greatest of These Is ... Rack Support
 
Class
ClassClass
Class
 
Php Reusing Code And Writing Functions
Php Reusing Code And Writing FunctionsPhp Reusing Code And Writing Functions
Php Reusing Code And Writing Functions
 

Kürzlich hochgeladen

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Kürzlich hochgeladen (20)

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 

Javascript Primer

  • 1. Javascript Primer The brainless dump of a brainless man Adam Hepton @ adamhepton 2010-2011, Frogtrade Image by Jeremy Richardson, &quot;Dead Frog&quot; March 25 2006 via Flickr, CC BY-NC-SA 2.0 (http://www.flickr.com/photos/jaded/151806291/)
  • 2. Arrays and objects [] = array {} = object var arr = []; var oldSchool = array(); var obj = {}; var oldObj = new Object(); var filledArr = [0, 1, &quot;two&quot;, 3, &quot;four&quot;]; var fullObj = {   &quot;key&quot; : &quot;value&quot;,   &quot;innerArray&quot; :     [3, &quot;more&quot;, &quot;things&quot;] }; This is JSON. Valid JSON uses double-quotes. For everything.
  • 3. Getting content from objects obj.x vs obj[x] obj.x means property 'x' from obj obj[x] means evaluate x, and find the result as a property of obj var obj = {   &quot;name&quot;:&quot;Adam&quot;,   &quot;age&quot;:30 }, fld = 'age'; > obj.name Adam > obj[name] name is not defined > obj.fld fld is not defined > obj[fld] 30
  • 4. Removing content from objects delete vs splice delete obj[key] array.splice(key, 1) var obj = { &quot;name&quot;:&quot;Adam&quot;, &quot;age&quot;:30 }, arr = [0, 1, 2, 3, 4]; > delete obj['age'] {&quot;name&quot;:&quot;Adam&quot;} > obj.splice(0, 1); obj has no method 'splice' > arr.splice(2, 1); [0, 1, 3, 4] > delete arr[1] [0, null, 3, 4] > arr.length 4
  • 5. Does it exist? typeof Check that something exists before you try and use it, or execution will break. var obj = {   &quot;name&quot;:&quot;Adam&quot;,   &quot;hoes&quot;:[718,202,901,305],   &quot;myFunc&quot;: function(i) {     alert(i);   } }; > var x = obj.func(); obj has no method 'func' > typeof obj.func undefined
  • 6. Verifying type typeof (cont.) var obj = {   &quot;name&quot;:&quot;Adam&quot;,   &quot;hoes&quot;:[718,202,901,305],   &quot;myFunc&quot;: function(i) {     alert(i);   } }; > typeof obj; object > typeof obj.myFunc function > typeof obj.hoes object > typeof null object
  • 7. I am not an object! typeof (cont) > typeof obj === typeof obj.hoes === typeof null; true > obj.hoes [718,202,901,305] > Object.prototype .toString.call(obj.hoes); [object Array] > obj.member = null; > typeof obj.member object > obj.member && typeof obj.member == 'object' false
  • 8. Getting info about objects for(var i in obj) To find all the properties of an object, iterate over the object with a for ... in var str = &quot;&quot;; for(var i in obj) {   if(typeof obj[i] == &quot;string&quot;) {     str += obj[i];   } } alert(string); I don't recommend using this on an array, because it is not very efficient - stick with for(i = 0; i < l; i++)  or, better still, while(i--) if you don't care about reverse ordering your array.
  • 9. Getting MOAR info about objects indexOf To find out whether something exists within an array, use indexOf. > arr.indexOf(&quot;doesn't exist&quot;) -1 Except in IE, where support for indexOf on arrays in patchy. You could add a simple version to the prototype, but this will affect a for ... in. The safest way is to use a helper function - if you have jQuery to hand, use $.inArray : if you don't, then roll your own.
  • 10. Accessing framed content .contentWindow To access the contents of an iframe, use contentWindow, and then continue your call from within that context. You can only manipulate a contentWindow if it is on the same domain (this includes sub-domains). var frameObj =  document.getElementById ('anIframe'); var frameBody = frameObj.contentWindow. document.body; frameBody.innerHTML = &quot;Changed HTML&quot;;
  • 11. Referencing windows parent.window To do something from within an iframe on the page that contains the iframe, use parent. You can only manipulate a parent window if it is on the same domain (this includes sub-domains). parent.update(a_variable); parent.window.update (a_variable); parent.document.getElement ById('test').innerHTML = 'New Content'; $('#test',parent.document) .html('New Content'); > parent === parent.window true
  • 12. Scoping Why no usey? Scoping is used to ensure variables are only accessible where they should be. (function() {   var private = 666;   var shh = function() {     alert(private);   };   secHole = function(x) {     private += x;   }; })(); > private private is not defined > shh() shh is not defined > secHole() 666
  • 13. Revealing Module Pattern Run that by me... var test = function() { var _private = 666; var public = 111; var fn = function() { console.log(_private); }; return { init: fn, p: public }; }(); If it's not in the return, it doesn't exist as far as the rest of the code is concerned Don't forget to execute the function, or you'll feel very foolish
  • 14. Keep it tight, yo > test.private private is undefined > test.fn fn is undefined > test.public public is undefined > test.init() 666 > test.p 111 var test = function() { var _private = 666; var public = 111; var fn = function() { console.log(_private); }; return { init: fn, p: public }; }();
  • 15. Evaluation Order Erm, what? var test = function() {   var x = 666;     var fn = function() {     console.log(x);   };   x = 999;   return {init: fn}; }(); > test.init() 999 Because everything is within a function, normal sequential ordering takes place as soon as the function is run for the first time. Good for inits.
  • 16. Calling within another scope Who gonna .call? Whenever you invoke a function, the this keyword is used to mean &quot;wherever it was called from&quot;, and usually, that means window, or the object where the function sits. You can tell a function to behave as though it was invoked from elsewhere, using .call: window.name = &quot;Thor&quot;; function bleh(i) {   console.log([this.name,     Math.sqrt(i)]); } var me = {&quot;name&quot;:&quot;Adam&quot;}; > bleh(65536); [&quot;Thor&quot;, 256] > bleh.call(me, 256); [&quot;Adam&quot;, 16]
  • 17. Calling within another scope (II) Read the .map If .call is used for firing one object into a function, .map is its big brother, used to iterate over an array: function foo(bar) {   return Math.pow(bar, 3); } var nums = [0,1,2,3,4]; > foo(5) 125 > var cub = nums.map(foo); [0, 1, 8, 27, 64] > console.log(nums) [0, 1, 2, 3, 4] Note the ordering difference between .call and .map: func.call(obj, param); arr.map(func);
  • 18. Calling within another scope (III) .reduce() If you wish to perform a function on all members of an array, and get a single result, .reduce is what you want: function foo(a, b) {   return (a * b) - 4; } var nums = [0,1,2,3,4]; > nums.reduce(foo); -164 > foo(0, 1) -4 > foo(-4, 2) -12 > foo(-12, 3) -40 > foo(-40, 4) -164
  • 19. Calling within another scope (IV) .reduce() more Reduce works by taking the previous value and the current value, but the function can also take the parameters of current index, and the array being worked on itself, should you need them: arr.reduce(   previous_value,   current_value,   [index,   original_array]);
  • 20. Interlude After the interlude: jQuery http://www.macwhirled.com/bacon.htm
  • 21. Getting Started $ To start using jQuery, use $. This is an alias to the jQuery object. To perform jQuery once the page and DOM have loaded (properly loaded, not just body onload loaded), use: $(document).ready( ... ); In Frog's PHP, there is a helper function, html_add_onload , which adds everything within the parameter to a $(document).ready function.
  • 22. Selectors The main use of $ $('div'); // all divs $('#anID'); // an element with an ID of 'anID' $('.frog3'); // all elements with a class of 'frog3' $('div a.special'); // all links with a class of special that have a parent (any depth) div $('div#container > ul.accordion > li'); // All list items that are a child of a UL with class 'accordion', which is a child of a div with class 'container' $('div.post + div.cmmt'); // Find all divs with class 'cmmt' that are next to a div with class 'post'
  • 23. Psuedo Elements &quot;Suede-o Element: is that something a bit like an element?&quot; - Alistair Gill $('div.post:first'); //or :last $('li.song:even'); $('li.song:gt(3)'); // or :lt(x) $('form#myForm :input'); // all inputs, selects, textareas – anything that can take input $('div#holder div:visible'); // all visible divs within the holder
  • 24. Working with Selectors Funsies! $('div.post').each(   function() {   alert($(this).height()); }); Callback function is within the scope of the element itself - as a DOM reference, not a jQuery object $('div.post').hide() .filter('.blog').show(); // find all divs with class 'post', hide them, and if they also have the class 'blog', show them. .filter is a superb method, because you can pass either a selector, or a function in, to get to just the elements you want
  • 25. Working with Selectors (II) Onesies! $('div.post').has('ul'); // find only posts that have a ul $('div.post').not('ul'); // find only ones that don't $('div.post, div.article, ul.menu').first(); // find the first of any of these selectors $('div#menu') .children('ul:first') .addClass('main').end() .next() .addClass('afterMenu'); // find the div id of menu, then its first child UL. Add a class of main to it, then go back to the menu. Find its next sibling, and add the class of afterMenu to it
  • 26. Manipulating Selectors Fonzie! $('div.post:first')   .html('<h1>FIRST</h1>' +   $(this).text()); // .html is innerHTML, .text is innerText.  Both getters and setters. if($('input#cName').val()   = frogBlue&quot;) {   $('input#cHex')     .val('#0071b9');   } } // .val is a getter and setter for input fields
  • 27. Manipulating Selectors (II) Ralph Malph! $('div.post:first')   .addClass('fClass'); $('div.post:last')   .removeClass('post'); $('div.post.eq(2)')   .toggleClass('frogBlue'); var $fP = $('div.post:first'); $fP.append('<h2>END</h2>'); $fP.prepend('<h1>1st</h1>'); $fP.remove('h2'); var $h = $fP.detach('h1'); $h.addClass('first')   .prependTo($fP); var $h2 = $h.clone(); $h2.removeClass('first')   .insertAfter($h);
  • 28. Traversing Selectors Ron Howard! var $fP = $('div.post:first'); $fP.next(); // or .prev(), can use a selector $fP.siblings('div.post'); // look in either direction $fP.children('div.commt'); // only one level deep $fP.find('p.commt'); // at any arbitrary depth $fP.parent(); // find the direct parent - can also use a selector $fP.parents('div.cnt'); // at any arbitrary depth upwards $fP.closest('div.hldr'); // iterate upwards, stop when found
  • 29. Compatibility with DOM jQuery obj v DOM var $fP = $('div.post:first'); // jQuery object var fP = $fP.get(0); // DOM Node $fP.attr('id') === fP.id; // finds the ID $fP.id === fP.attr('id'); // error $('div.post').each(   function() { alert(this.id); alert($(this).attr('id')); });
  • 30. Browser Differences Browser v Feature There are two types of difference between browsers. It's too easy to say, &quot;This is just not working in IE7, so I'll do something for IE7&quot;. More often, it's a feature that's different in one (or two) browsers than another, so you should use feature detection, where possible. $.support gives a nice list of things that are known to be different in certain browsers, so check for that. Also, modernizr.com is helpful, but not used in Frog at the moment. output of $.support for Chrome 12
  • 31. Optimisation Familiarisation var $divs = $('div'); Store your selectors, if you use them more than once, and they don't change. .each is bad! Closures are bad! $('div').each(function() { $(this).addClass('blue'); }); THE UGLY var addBlue = function() { $(this).addClass('blue'); }; $('div').each(addBlue); THE BAD $('div').addClass('blue'); THE GOOD, THE ONLY
  • 32. Optimisation (II) Just a nature walk Assigning event handlers to lots of elements is wasteful. Add them to the parent element for FUN TIMES. $('#on div.clk')   .bind('click',     function() { $(this).toggleClass('on'); }); What if we add new ones? What if there are 500 of them? $('#on').bind('click', function(e) { if($(e.target)     .is('div.clk')) {       $(e.target)       .toggleClass('on');     } });
  • 33. So Long Suckers! I hate you all