JQuery Coding Standards

Follow Drupal’s JavaScript coding standards


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


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:

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

Avoid Internet Explorer errors


Use JQueryMetadata to integrate jQuery plugins into Foswiki.


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


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

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