JQuery Coding Standards

Follow Drupal’s JavaScript coding standards

Shorthands

Use the jQuery shorthand $ where possible:

$(function() { ... });

instead of

$(document).ready(function() { ... });

Wrap $

If you want to use jQuery’s $ variable, wrap your code like this:

(function($) {

  // code using $ variable

})(jQuery);

Global variables

If you want to use global variables within the scope of your code, wrap your code like this:

(function() {

  var foo = 'bar'; // yay, it's almost like I'm global

})();

If you want to use global variables in the global scope, put the variable in the foswiki namespace:

foswiki.foo = 'bar';

Mind the predefined global variables. See next section.

Propagating perl settings to javascript

The jquery.foswiki plugin will initialize the global foswiki object with a set of variables that are created by reading meta tags in the HTML header. These have the format

<meta name="foswiki.foo.bar.baz" content="string/boolean/object/function" />

The foswiki object

This will create the appropriate sub-namespaces and initialize the named property with the value in the content attribute.

There is a set of predefined variables that can be used in your javascript code via the foswiki namespace:

NameSorted descending Content
foswiki.wikiUserName %WIKIUSERNAME%
foswiki.wikiName %WIKINAME%
foswiki.web %WEB%
foswiki.usersWebName %USERSWEB%
foswiki.topic %TOPIC%"
foswiki.systemWebName %SYSTEMWEB%
foswiki.serverTime %SERVERTIME%
foswiki.scriptUrlPath %SCRIPTURLPATH%
foswiki.scriptUrl %SCRIPTURL%
foswiki.pubUrlPath %PUBURLPATH%
foswiki.pubUrl %PUBURL%
foswiki.MathModePluginEnabled %IF{"context MathModePluginEnabled" then="true" else="false"}%
foswiki.loginName %USERNAME%
foswiki.ImagePluginEnabled %IF{"context ImagePluginEnabled" then="true" else="false"}%

Avoid Internet Explorer errors

Metadata

Use JQueryMetadata to integrate jQuery plugins into Foswiki.

LiveQuery

Use JQueryLiveQuery to initialize your plugin for all html elements of a page. Otherwise content that is loaded asynchronously using ajax won't be initialized. LiveQuery will take care of that automatically.

Instead of

$(".jqPluginName").each(function() {
  // initializer
});

use

$(".jqPluginName").livequery(function() {
  // initializer
});

See JQueryMetadata for a more thorough example of useing metadata and livequery

spacer