Skip to content
Adam Norris edited this page May 14, 2018 · 1 revision

For clarity, prefix jQuery variables with $

var $myDiv = $('.myDiv');

Cache elements to avoid traversing the DOM unnecessarily

Keep callbacks to a minimum. Consider refactoring into functions if the code starts to look messy and confusing to read.

Make use of jQuery's document.ready() function to ensue the DOM is loaded and to prevent global variables being set.

$(document).ready(); or $(function)

Always bind events with jQuery rather than using javascript inlining

<!-- Bad -->
<a class="myLink" onclick="myEventHandler();">
// Better
$('.myLink').on('click', myEventHandler);

Don't use jQuery to add styles directly, instead use class names

// Bad
$('myDiv').css('color', 'red');

// Better
$('myDiv').addClass('error');

See jQuery's Javascript style guide for more information

Clone this wiki locally