$('.click').click(function(){}); $('.click').css({'color': 'red'}); $('.click').hover( makeMeCoffee );
Closures and Variable Scope. The ‘var’ keyword. When to prefix.
// Ommitting the 'var' keyword, myArray = ['one', 2, 'three', 4]; // Or having the variable sit outside of a closure var myArray = ['one', 2, 'three', 4]; // it becomes a global.. BAD
prefixMyVar = 'Some global thing';
// Better, use a self-executing anonymous function to contain your vars in a "closure" (function(){ var myArray = ['one', 2, 'three', 4]; })();
Namespaces and global objects.
window.myGlobalVar = { myArray : ['one', 2, 'three', 4], myObject : {'zero' : 0, 1 : 'one'}, myFunc : function() { alert('myFunc'); }; };
window.myGlobalVar = {}; myGlobalVar.myArray = ['one', 2, 'three', 4]; myGlobalVar.myObject = {'zero' : 0, 1 : 'one'}; myGlobalVar.myFunc = function() { alert('myFunc'); };
Namespaces and global objects.
(function(window, document, $, undefined){ // 'window.myVar' is like `global $my_var;` in php window.myGlobalVar = {}; // Shorthand local variable var globvar = myGlobalVar; // Add my vars and methods to the global var object globvar.myArray = ['one', 2, 'three', 4]; globvar.myObject = {'zero' : 0, 1 : 'one'}; globvar.myFunc = function() { alert('myFunc'); }; })(window, document, jQuery);
Think about other devs coming behind you..
jQuery.ready(function(){});
=== bad// This is better.. myGlobalVar.init = function( $ ) { // Do stuff... } // the init method is reachable by other devs jQuery.ready( myGlobalVar.init );
An Aside: The difference between array and objects
// This is an array WDSLunch.myArray = ['zero', 1, 'two', 3]; // WDSLunch.myArray[0] == 'zero'
// This is an object WDSLunch.myObject = {'zero' : 0, 1 : 'one', 'two' : 2, 3 : 'test'}; // WDSLunch.myObject['two'] === 2 (can also use WDSLunch.myObject.two)
// This is an array of objects WDSLunch.myObjectArray = [ {'zero' : 0}, {1 : 'one'}, {'two' : 2} ]; // WDSLunch.myObjectArray[1] === {1 : 'one'}
$('body').on( 'click', '.button', function(){}) > $( '.button' ).click(function(){})
.css()
(and even .show()
and .hide()
).. Better to keep your css in your .css, and add/remove classes.
$('.button').removeClass( 'hide' ).addClass( 'show class-for-styling' );
function myFunc() { var text = 'my text'; }
$
at the front of these variables to indicate a jQuery object).
var $body = jQuery( 'body' ); var $content = $body.find( '.content' ); var clickHandler = function( event ) { event.preventDefault(); // do stuff... } $content.on( 'click', '.click-me', clickHandler );
(because DRY = Don’t repeat yourself!)
'use strict';
(no really…use 'use strict';
)