jQuery
- Prefix jQuery object variables with a
$
.
// 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
});