Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Javascript Primer


Published on

When I left Frogtrade, I was asked to provide a presentation on Javascript basics to act as reference material for the PHP developers I left behind. This is that presentation.

Published in: Technology
  • Be the first to comment

Javascript Primer

  1. 1. 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 (
  2. 2. 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.
  3. 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 = {   "name":"Adam",   "age":30 }, fld = 'age'; > Adam > obj[name] name is not defined > obj.fld fld is not defined > obj[fld] 30
  4. 4. 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
  5. 5. 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
  6. 6. 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
  7. 7. I am not an object! typeof (cont) > typeof obj === typeof obj.hoes === typeof null; true > obj.hoes [718,202,901,305] > Object.prototype; [object Array] > obj.member = null; > typeof obj.member object > obj.member && typeof obj.member == 'object' false
  8. 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. 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. 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. 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. 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. 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. 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. 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. 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: = &quot;Thor&quot;; function bleh(i) {   console.log([,     Math.sqrt(i)]); } var me = {&quot;name&quot;:&quot;Adam&quot;}; > bleh(65536); [&quot;Thor&quot;, 256] >, 256); [&quot;Adam&quot;, 16]
  17. 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 =; [0, 1, 8, 27, 64] > console.log(nums) [0, 1, 2, 3, 4] Note the ordering difference between .call and .map:, param);;
  18. 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. 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. 20. Interlude After the interlude: jQuery
  21. 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. 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.cmmt'); // Find all divs with class 'cmmt' that are next to a div with class 'post'
  23. 23. Psuedo Elements &quot;Suede-o Element: is that something a bit like an element?&quot; - Alistair Gill $(''); //or :last $(''); $(''); // 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. 24. Working with Selectors Funsies! $('').each(   function() {   alert($(this).height()); }); Callback function is within the scope of the element itself - as a DOM reference, not a jQuery object $('').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. 25. Working with Selectors (II) Onesies! $('').has('ul'); // find only posts that have a ul $('').not('ul'); // find only ones that don't $(', div.article,').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. 26. Manipulating Selectors Fonzie! $('')   .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. 27. Manipulating Selectors (II) Ralph Malph! $('')   .addClass('fClass'); $('')   .removeClass('post'); $('')   .toggleClass('frogBlue'); var $fP = $(''); $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. 28. Traversing Selectors Ron Howard! var $fP = $(''); $; // or .prev(), can use a selector $fP.siblings(''); // 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. 29. Compatibility with DOM jQuery obj v DOM var $fP = $(''); // jQuery object var fP = $fP.get(0); // DOM Node $fP.attr('id') ===; // finds the ID $ === fP.attr('id'); // error $('').each(   function() { alert(; alert($(this).attr('id')); });
  30. 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, is helpful, but not used in Frog at the moment. output of $.support for Chrome 12
  31. 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. 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($(     .is('div.clk')) {       $(       .toggleClass('on');     } });
  33. 33. So Long Suckers! I hate you all