Skip to main content

jQuery

  • Prefix jQuery object variables with a $.
// bad
const sidebar = $('.sidebar');

// good
const $sidebar = $('.sidebar');

// good
const $sidebarBtn = $('.sidebar-btn');
  • Cache jQuery lookups.
// bad
function setSidebar() {
  $('.sidebar').hide();

  // ...

  $('.sidebar').css({
    'background-color': 'pink',
  });
}

// good
function setSidebar() {
  const $sidebar = $('.sidebar');
  $sidebar.hide();

  // ...

  $sidebar.css({
    'background-color': 'pink',
  });
}
  • Use find with scoped jQuery object queries.
// bad
$('ul', '.sidebar').hide();
$('.sidebar').find('ul').hide();
$('.sidebar').children('ul').hide();

// good
$('.sidebar ul').hide();
$('.sidebar > ul').hide();
$sidebar.find('ul').hide();
  • Handle failure and complete events when performing AJAX calls.
$.getJSON('http://example.com/json', (data) => {
  // Do something with the JSON data
}).fail((jqXHR, textStatus, errorThrown) => {
  // Show an error message
}).always(() => {
  // Hide a loading indicator if required
});