JavaScript best practices
Progressive enhancement
JavaScript solutions must exist purely as a progressive enhancement of existing functionality.
DOM binding
When attaching JavaScript behaviour to a specific DOM element, we favour data-attributes in the markup rather than class names or an ID:
- It helps to maintain the separation of concerns
- It avoids JavaScript breaking due to the accidental renaming of a class
- It avoids a developer unwittingly removing a class that is not referenced by any CSS files
When using JavaScript to add a class to a specific DOM element, start the class name with the js-
prefix to make it clear where the class has come from.
Event handlers
To ensure accessibility, use either a device-independent event handler (one that works with both the mouse and the keyboard) or use both mouse- and keyboard-dependent event handlers.
Mouse-dependent event handlers
onmouseover
onmouseout
onhover
Keyboard-dependent event handlers
onkeyup
/onkeydown
Device-independent event handlers
onfocus
;onblur
onchange
;onselect
onclick
(use only with keyboard-navigable - i.e. real - links and form controls)