This repository has been archived by the owner on Dec 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Coding standard for javascript
osj2507 edited this page Mar 16, 2013
·
1 revision
###Guidelines for Javascript & jQuery
- Use camelCase for naming javascript variables and functions.
- Use PascalCase for naming javascript "classes". It helps to show which functions that are instantiated with the 'new' operator.
- Never use Javascript for styling elements. Use it to add/remove CSS classes which are then styled in CSS. The only exception to this rule is for animation purposes.
- Never prepend an id with a tagName. E.g. don’t: $(“div#my-id”); - It’s bad for perfomance.
- Avoid explicit event handling in HTML. Do the binding of event handlers in the javascript file.
<!-- Bad -->
<span id=”my-span” onclick=”runMyFunction(); return false;”></span>
// Good
$("#my-span").on("click", function(){
runMyFunction();
return false;
});
- Always cache jQuery objects/selections for later use.
// Bad - causes two DOM searches for the ".button" class
$(".button").toggle();
$("#form").append($(".button"));
// Good - keeps the DOM element in memory
var $buttons = $(“.button”);
$buttons.toggle();
$("#form").append($buttons);
- Always declare variables with the
var
keyword or they will be defined in the global scope. - Prepend variable names with $ if it holds a jQuery object.
var $mySpan = $("#my-span");
var review = $("review-body").val();
- Use
$(window).load(function(){ … });
instead of$(document).ready(function(){ … });
when your code is not related to rendering the page. E.g. when binding click events. - Use event delegation instead of event handling when possible. Especially when binding several events/handlers - It improves performance.
// Bad - loops all elements and does a bind for each
$(".all-my-buttons").bind("click", function(){
$(this).hide();
});
// Good - Only binds one event, but delegates the handling.
// Bonus - This handling also works if the buttons are created dynamically! Which won't work on a normal bind() method.
$("#button-wrapper").on("click", ".all-my-buttons", function(){
$(this).hide();
});
- Declare variables on several lines.
// Bad
var a, b, c;
// Good
var a;
var b;
var c;