Continuing with jQuery

Tips, tricks, and useful plugins for the JavaScript ninja



Created by Brian Duffey

Who am I?


  • Brian Duffey
  • 4 years consultant at michaels, ross, and cole
    m-Power
  • 15 years of JavaScript experience
  • 4+ years jQuery developer
  • What have I used jQuery for?

What are we here for?

  1. Introduction
    • Junior, Senior, Ninja
  2. Tips
    • Variables
    • Comparisons
    • Functions
    • DOM
    • Errors
    • Customize
  3. Tricks
    • Common Tasks
    • Arrays
  4. Plugins

What are we here for?

  1. Introduction
    • Junior, Senior, Ninja
  2. Tips
    • Variables
    • Comparisons
    • Functions
    • DOM
    • Errors
    • Customize
  3. Tricks
    • Common Tasks
    • Arrays
  4. Plugins

Junior, Senior, & Ninja Programmers


- 10 minutes - 1 day - 10-15 minutes
- 2 days - 1 day - 10 minutes

What are we here for?

  1. Introduction
    • Junior, Senior, Ninja
  2. Tips
    • Variables
    • Comparisons
    • Functions
    • DOM
    • Errors
    • Customize
  3. Tricks
    • JavaScript
    • jQuery
  4. Plugins

Tips

Variables

            
x = 3;
            
          
            
function myFunc() {
  x = 3;
  y = 4;
  // More code below here that uses x and y
}
            
          

Tips

Variables - Scope

Def.:
the set of variables,
objects, and functions
you have access to
                  
var x = 3; // Global
function myFunc(z) {
  var y = 4; // Function level
}

function otherFunc() {
  var z = 5; // Local
  myFunc(z);
}
                  
                
                  
function myFunc() {
  var x = 3;
}
                  
                
                  
// All 3 are global
var x = 3;
function myFunc() {
  window.x = 3;
  x = 3;
}
                  
                
                  
function myFunc() {
  var x = 3,
      y = 4,
      z = 5;
}
                  
                

Tips

Variables - Complex

                  
var counter = 1, // number
    aName = 'John', // string
    isAlive = true; // boolean
                  
                
                  
var anArray = [1, 'John', true];
var anArray = new Array();
                  
                
                  
var Person = {
  name:'',
  age:0,
  isAlive:true,
  createPerson:function(nm,ag,ia) {
    this.name = nm;
    this.age = ag;
    this.isAlive = ia;
    return this;
  }
};
                  
                
                  
var steve = new Person.createPerson('Steve', 33, true);
                  
                
                  
var names = ['John', 'Fred', 'Bill'];
                  
                
                  
var steve = new Person.createPerson('Steve', 33, true),
    susan = new Person.createPerson('Susan', 21, true),
    betty = new Person.createPerson('Betty', 96, false),
    people = [steve, susan, betty];
                  
                

Tips

Variables - Objects for Scope

                  
var chimp = {
      name:'Bobo',
      type:'chimpanzee'
    },
    giraffe = {
      name:'Jeffrey',
      type:'giraffe'
    },
    otter = {
      name:'Ollie',
      type:'otter'
    },
    zoo = [chimp, giraffe, otter];
                  
                
                  
var Zoo = {
      animals:[],
      addAnimal:function(nm, tp) {
        this.animals.push(new Animal.createAnimal(nm, tp));
      }
    },
    Animal = {
      name:'',
      type:'',
      createAnimal:function(nm, tp) {
        this.name = nm;
        this.type = tp;
        return this;
      }
    };
Zoo.addAnimal('Bobo', 'chimpanzee');
Zoo.addAnimal('Jeffrey', 'giraffe');
Zoo.addAnimal('Ollie', 'otter');
                  
                

Tips

Variables - String Concatenation

jsPerf.com

            
str = str + i;

str += i;

str = str.concat(i);

str = [str, i].join('');
            
          

Tips

Comparisons

            
// Booleans
x = true;  // true
y = !x; // false
z = 1 < 0; // false

// Comparisons
if (x) {
  // success
} else {
  // failure
}

result = (x) ? success : failure; // results in success
            
          

Tips

Comparisons - Type Coercion

            
var x = 1, // number
    y = '1'; // string
x == y; // true
            
          
            
x === y; // false
x !== y; // true
            
          

Tips

Comparisons - Falsy Values

  • 0
  • ''
  • null
  • undefined
                  
var age = prompt('What is your age?');
if (age) {
  // do something
} else {
  // print error
}
                  
                
                  
var donation = prompt('How much would you like to donate?');
if (donation) {
  // do something
} else {
  // print error
}
                  
                

Tips

Comparisons - Conditions

                  
if (someCondition) {
  // do something
} else {
  // do something else
}

x = (anotherCondition) ? someResult : someOtherResult;
                  
                
                  
switch(someValue) {
  case 1:
    // do something
  default:
    // do something else
}
                  
                
                  
var state = prompt('What state are you from?');
switch(state) {
  case 'California':
  case 'Florida':
  case 'Hawaii':
    alert('Nice weather there!');
    break;
  case 'Alaska':
    alert('Sounds cold!');
    break;
  default:
    alert('Never heard of it!');
}
                  
                
  • Switches - 3-10 cases
  • If/Else - 1, 2, 10+

Tips

Comparisons - jQuery Objects

                  
var rightButton = jQuery('#rightButton');
jQuery('button').click(function() {
  if (jQuery(this) == rightButton) {
    // do something
  }
});
                  
                
                  
var rightButton = jQuery('#rightButton');
jQuery('button').click(function() {
  if (jQuery(this).is(rightButton)) {
    // do something
  }
});
                  
                
                  
jQuery('#myID') == jQuery('#myID'); // false
                  
                
                  
jQuery('#myID').is('#myID'); // true
                  
                

Tips

Functions

JavaScript jQuery
Math.random jQuery.trim
isNaN hide
parseInt show
toFixed toggle
indexOf is
substring click

Tips

Functions - Creating

                  
function yourAge() {
  var age = prompt('What is your age?');
  if (age) {
    alert('Your age is ' + age);
  } else {
    alert('Fine, don\'t tell me');
  }
}
                  
                
                  
function func1() {
  // do some stuff
}
function func2() {
  // do some more stuff
}

// the rest of your code
                  
                
                  
function getAge() {
  var age = prompt('What is your age?');
  return age;
}

function yourAge(age) {
  if (age) {
    alert('Your age is ' + age);
  } else {
    alert('Fine, don\'t tell me');
  }
}
                  
                
                  
var func3 = function() {
  // do yet more stuff
}
                  
                

Tips

Functions - Files

  • Create external files
                    
    
                    
                  
  • Code minification

Tips

Functions - IIFE

Immediately Invoked Function Expression

                  
(function() {
  // immediately invoked code here
}());
                  
                
                  
(function(j) {
  // my jQuery plugin code here
}(jQuery));
                  
                

Tips

Functions - Logicals

  • AND - &&
  • OR - ||
                  
x = true;
y = false;
x && y; // false
x || y; // true
                  
                
                  
if (item.weight < 301) {
  loadTruck(item);
}

(item.weight > 300) || loadTruck(item);
                  
                
                  
if (person.age > 20) {
  person.serveBeer();
}

(person.age > 20) && person.serveBeer();
                  
                
                  
function canVote(age) {
  age = age || 17;
  return (age > 17);
}
                  
                

Tips

DOM

Document Object Model

Tips

DOM - Simplify

  • Limit elements
                          
          jQuery('*').length;
                          
                        
  • Keep selectors simple
                          
          jQuery('#someID')... // fast
          jQuery('body div.someClass input[value=""]')... // slow
                          
                        
  • Know how selectors are parsed
                          
    jQuery('#someID p')... // slow
    jQuery('#someID').find('p')... // fast
    jQuery('p', '#someID')... // fast
                          
                        
  • Know performance of selectors
                          
    jQuery('#someID')... // fastest
    jQuery('p')... // fast
    jQuery('.someClass')... // slow
    jQuery(':visible')... // slowest
                          
                        

Tips

DOM - Cache

Chaining

                  
// Without chaining
jQuery('div').css('color', 'red');
jQuery('div').css('backgroundColor', 'blue');

// With chaining
jQuery('div').css('color', 'red')
  .css('backgroundColor', 'blue');
                  
                
                  
jQuery('input').each(function() {
  if (this.value === jQuery('p').text()) {
    // do something
  }
});
                  
                
                  
var p = jQuery('p');
jQuery('input').each(function() {
  if (this.value === p.text()) {
    // do something
  }
});
                  
                
                  
var myText = jQuery('p').text();
jQuery('input').each(function() {
  if (this.value === myText) {
    // do something
  }
});
                  
                

Tips

DOM - Propagation

                  
jQuery('button').click(function() {
  // do something
});
                  
                
                  
jQuery('.menu').click(function(e) {
  // do something here
});
jQuery('.menuItem').click(function(e) {
  // do the same thing here
  e.stopPropagation();
});
                  
                
                  
jQuery('.menu').click(function() {
  // do something here
});
jQuery('.menuItem').click(function() {
  // do the same thing here
});
                  
                
                  
jQuery('.menu').click(function() {
  if (this.id === 'menuItem1') {
    // do something here
  } else {
    // do something else
  }
});
                  
                

Tips

DOM - Reflows/repaints

  • Repaints - Occurs when changes are made to an element's appearance that does not affect its layout
  • Reflows - Occurs when changes are made to the layout of a page
  • Minimize by
    • Apply changes in bulk
                          
      jQuery('#someID').css('color', 'red');
      jQuery('#someID').css('backgroundColor', 'white');
      jQuery('#someID').css('border', '1px solid blue');
      
      jQuery('#someID').addClass('chicagoCubs');
                          
                        
    • Operate on hidden/copied element
    • Avoid reflows (slow performance!) by changing layout as little as possible

Tips

Errors


Tips

Errors - Debugging

  • Print values
                          
    alert('The value of x is: ' + x);
                          
                        
                          
    console.log('The value of x is: ' + x);
                          
                        
  • Step through code

Tips

Errors - Try-catch

                  
try {
  // do something
} catch(err) {
  // handle error here
}
                  
                
                  
try {
  // do something
} catch(err) {
  // handle error here
  console.error('Oh no!  Error occurred: ' + err);
} finally {
  // run some code regardless of errors
}
                  
                
                  
try {
  // do something
} catch(err) {
  // handle error here
  console.error('Oh no!  Error occurred: ' + err);
}
                  
                
                  
try {
  // do something
  throw 'x is missing a value';
} catch(err) {
  // handle error here
  console.error('Oh no!  Error occurred: ' + err);
}
                  
                

Tips

Errors - JSLint

  • JSLint.com
    "JSLint is a JavaScript program that looks for problems in JavaScript programs. It is a code quality tool."


Tips

Errors - Timing

performance.now

            
var start = performance.now(),
    end, elapsed;
/* my code
 * runs in
 * this block */
end = performance.now();
elapsed = end - start;
console.log('MS elapsed: ' + elapsed);
              
            

Tips

Customize

Tips

Customize - jQuery



  • Know what jQuery offers you as a developer
  • Know what it does not

Tips

Customize - Add to jQuery

                  
jQuery('tr').each(function() {
  if (jQuery(this).find('th').length === 0) {
    // do something with this row
  }
});
                  
                
                  
jQuery.extend(jQuery.expr[':'], {
    nonHead: function(a) {
        return jQuery(a).find('th').length === 0;
    }
});
                  
                
                  
jQuery('tr:nonHead')... // do something with each row
                  
                
                  
jQuery('input[type="checkbox"]').each(function() {
  jQuery(this).prop('checked', true);
});
                  
                
                  
jQuery.fn.check = function() {
  this.prop('checked', true);
}
                  
                
                  
jQuery('input[type="checkbox"]').check();
                  
                

Tips

Customize - Plugins

  • Create your own
  • Share with other developers
  • Custom plugins use IIFE form
  • Use official jQuery Repository

Tips

Customize - Exists

  • Does not work to check if falsy
                    
    if (jQuery('#someID')) {...} // will always be true
                    
                  
  • This does work
                    
    if (jQuery('#someID').length) {...} // will only be true if at least one is found
                    
                  
  • You can add to jQuery to use
                    
    jQuery.fn.exists = function() {
      return this.length > 0;
    }
    
    if (jQuery('#someID').exists()) {...} // easier to understand what you are doing
                    
                  

What are we here for?

  1. Introduction
    • Junior, Senior, Ninja
  2. Tips
    • Variables
    • Comparisons
    • Functions
    • DOM
    • Errors
    • Customize
  3. Tricks
    • JavaScript
    • jQuery
  4. Plugins

Tricks

JavaScript vs. jQuery

          
// using attr function
var theID = jQuery('p').attr('id');

// converting jQuery object to JS with get
var theID = jQuery('p').get(0).id;
          
        
          
jQuery('button').click(function() {
  // common way in jQuery
  var theID = jQuery(this).attr('id');
});
          
        
          
jQuery('button').click(function() {
  // better way using vanilla JS
  var theID = this.id;
});
          
        

Tricks

JavaScript - Loops

jsperf.com
            
for (var i = 0; i < els.length; i++) {
    // do something with each item of els
}
            
          
            
for (var i = 0, iLen = els.length; i < iLen; i++) {
    // do something with each item of els
}
            
          
            
for (var i = els.length; i--;) {
    // do something with each item of els
}
            
          

Tricks

JavaScript - Arrays

            
var arr = new Array();
var arr = [];
            
          
            
var max = Math.max.apply(Math, arr); // max has max value from arr
var min = Math.min.apply(Math, arr); // min has min value from arr
            
          
            
arr.length = 0; // empty array
arr.length = 4; // truncate array to 4 values
            
          
            
delete arr[3]; // item 4 in arr will now be undefined
arr.splice(3, 1); // item 4 is now completely gone from arr
            
          
            
var arr2 = arr.map(function(val) {
  return val * val;
});
// arr2 now holds all the original values of arr, but squared
            
          

Tricks

jQuery - Events

            
jQuery('button').click(function() {
  alert('Button was clicked!');
});
            
          
            
jQuery('body').on('click', 'button', function() {
  alert('Button was clicked!');
});
            
          
            
jQuery('button').on('click', function() {
  alert('Button was clicked!');
});
            
          

Tricks

jQuery - End

            
jQuery('div').find('p').css('backgroundColor', 'red');
jQuery('div').find('span').css('backgroundColor', 'blue');
            
          
            
jQuery('div').find('p').css('backgroundColor', 'red')
  .end().find('span').css('backgroundColor', 'blue');
            
          

Tricks

Types

JavaScript

          
typeof ''; // string
typeof 0; // number
typeof null; // object
typeof new Date(); // object
typeof []; // object
typeof {}; // object
          
        

jQuery

          
jQuery.type(''); // string
jQuery.type(0); // number
jQuery.type(null); // null
jQuery.type(new Date()); // date
jQuery.type([]); // array
jQuery.type({}); // object
          
        

What are we here for?

  1. Introduction
    • Junior, Senior, Ninja
  2. Tips
    • Variables
    • Comparisons
    • Functions
    • DOM
    • Errors
    • Customize
  3. Tricks
    • JavaScript
    • jQuery
  4. Plugins

Plugins

Before Plugins | After Plugins


Plugins

Date Selection

  • jQuery UI Datepicker
  • Part of the jQuery UI library
  • Offers such things as:
    • Dragging and/or dropping
    • Resizing
    • Selecting
    • Sorting
    • Sliders and spinners
    • Tabs, menu, accordions
    • Etc.
  • Datepicker very useful to handle date-related selections

Plugins

Dates

Moment.js

  • Easily read in strings to get dates
  • Manipulate dates easily:
    • Add/subtract
    • Get difference between two dates
    • Get first of/end of easily
    • Etc.

Plugins

Numbers

Numeral.js

  • Numeral.js was built upon the same foundation as moment.js
  • Very similarly used, but for numbers instead of dates
  • Great for any situation you need to either read in a string as a number or print a formatted number

Plugins

Validating

jQuery Validation

  • Great for validating user input
  • One of the oldest ones (since July 2006)
  • Has many useful methods for validating built-in
  • You can fully customize this plugin including writing your own validation

Plugins

Storing Data

jQuery Cookie

  • Cookies are great for storing non-sensitive information
  • Key-value pairs, can also have a path and an expiration date
  • Very easy to set, retrieve, or remove cookies for your site

Plugins

Alerts

Alertify.js

  • Browsers provide built in ways to call alerts, confirmations, or prompts
  • However, these are kind of ugly and differ across browsers
  • Alertify pretties up alerts and even allows growl-like notifications
  • This can be used anywhere you would normally use an alert, confirm, or prompt

Plugins

Formatting

Masked Input

  • There are many inputs that might be amibiguous to users
  • Some examples include:
    • Phone Numbers
    • Dates
    • SSN
    • Etc.
  • In these cases, you can force the input into a specified format

Plugins

Plugins

Head.js

  • Plugins are useful an great, but can make your page slow/bloated
  • File managers help you keep your code clean
  • Head.js loads only what you need, when you need it
  • The more JS files you bring in to your page, the more useful this is

That's it!

Questions? Comments?

Links

Credits

  • http://modernweb.com/2013/12/23/45-useful-javascript-tips-tricks-and-best-practices/
  • http://developer.blackberry.com/html5/documentation/v2_2/javascript_best_practices.html
  • https://github.com/jed/140bytes/wiki/Byte-saving-techniques
  • http://gregfranko.com/blog/i-love-my-iife/
  • http://tutorialzine.com/2011/06/15-powerful-jquery-tips-and-tricks-for-developers/
  • jQuery Trickshots -100 Advanced Techniques (2015 Edition) from tutorialzine.com
  • Images from https://openclipart.org