jQuery coding standards
| Project: | Documentation |
| Component: | New documentation |
| Category: | task |
| Priority: | normal |
| Assigned: | Unassigned |
| Status: | active |
| Issue tags: | coding standards |
Jump to:
It seems we could use some specific examples and guidelines for jQuery coding standards.
Here are some rough suggestions for examples we could provide:
1. Indent a function definition, EG:
fieldset.bind('summaryUpdated', function () {
var text = $.trim(fieldset.getSummary());
summary.html(text ? ' (' + text + ')' : '');
})
2. Keep jQuery calls at the same level when they act sequentially on the same object, EG:
.append(fieldset.hasClass('collapsed') ? Drupal.t('Show') : Drupal.t('Hide'))
.after(' ')
.andSoOn()
.andSoOn()
3. Indent lines when we use a new variable to start a chain of actions on a different object. In this example, the .append applies to the div, not the same element the .after applies to:
.after($('')
.append(fieldset.children(':not(legend):not(.action)'))
);
4. Indent when .find() starts a chain of actions on a different object, EG:
.removeClass('collapsed')
.find('> legend > a > span.element-invisible')
.empty()
.append(Drupal.t('Hide'));
5. Do not end a line with ".", instead start "." on a new line.
Do not do this BAD thing:
fieldset.
bind(...
Instead do this GOOD thing:
fieldset
.bind(...
6. Close parentheses and brackets at the same indent level as the start of the line where they were opened. Stack them when we close two or more that start at the same depth. EG, the closing parens are on different lines but the last line has a closing bracket and paren together because they were both started together:
$('fieldset.collapsible > legend', context).once('collapse', function () {
$(this).empty().append($('' + text + '')
.prepend($('')
.append(fieldset.hasClass('collapsed') ? Drupal.t('Show') : Drupal.t('Hide'))
.after(' ')
)
)
});
7. It is okay to stack repeated/related jQuery calls on the same line, EG $(this).empty().append in the above snippet.
This is all just an idea to start the discussion.
This was prompted by conversations in the issue queue and irc with @tha_sun about misc/collapse.js in #541568: Link to expand / collapse fieldsets has poorly accessible link text. The existing indents and formatting were inconsistent in collapse.js and presumably elsewhere.

#1
subscribing
#2
Tagging.
#3
this seems like it would fit nicely in here: http://drupal.org/coding-standards if you can add it as a page... (and we'll have to get it reviewed)