Skip to content

JS Guidelines

Elisabeth Hamel edited this page Jan 18, 2017 · 20 revisions

The examples are written in jQuery but the guidelines are also valid in VanillaJS.

Selectors

Use IDs to select elements used in JS. This is better for performance and as we are not using IDs in CSS, it allows us to see directly in the HTML which elements are used in JS.

If you must use a class, add a specific class not used in CSS with the "js-" prefix.

Avoid excessive specificity: https://learn.jquery.com/performance/optimize-selectors/

Prefer the use of the "find" function.

Bad

$('#list li a');

Better

$('#list a');

Good

$('#list').find('a');

Events binding

Try to delegate all your events binding: https://learn.jquery.com/events/event-delegation/

Bad

$('li').on('click', function(){
    // do something
});

Good

$('#list').on('click', 'li', function(){
    // do something
});

Clone this wiki locally