You are here: CTSPedia>System Web>JQueryPlugin>JQueryCodingStandards (14 Jul 2010, AdminUser?)EditAttach
create new tag
, view all tags, tagging instructions


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: = '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="" 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 Content
foswiki.web %WEB%
foswiki.topic %TOPIC%"
foswiki.scriptUrl %SCRIPTURL%
foswiki.scriptUrlPath %SCRIPTURLPATH%
foswiki.pubUrl %PUBURL%
foswiki.pubUrlPath %PUBURLPATH%
foswiki.systemWebName %SYSTEMWEB%
foswiki.usersWebName %USERSWEB%
foswiki.wikiName %WIKINAME%
foswiki.loginName %USERNAME%
foswiki.wikiUserName %WIKIUSERNAME%
foswiki.serverTime %SERVERTIME%
foswiki.ImagePluginEnabled %IF{"context ImagePluginEnabled" then="true" else="false"}%
foswiki.MathModePluginEnabled %IF{"context MathModePluginEnabled" then="true" else="false"}%

Avoid Internet Explorer errors

  • Use an object if you need an associative array, not an array. [source]
  • Declare all local variables with var before they are used.
  • Remove trailing commas from array and object definitions, i.e.:
    var object = { foo: 'bar' }
    var object = { foo: 'bar', }


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

Topic revision: r3 - 14 Jul 2010 - 14:43:53 - AdminUser?
This site is powered by FoswikiCopyright & by the contributing authors. All material on this site is the property of the contributing authors.
Ideas, requests, problems regarding CTSPedia? Send feedback