Skip to main content

jQuery

Deprecated 3.8

The use of jQuery in new code is strongly discouraged and is not generally accepted in core. Specific exceptions to this rule are made on a case-by-case basis, generally when interfacing with legacy code which expects to be passed a jQuery object.

Moodle has supported the use of native ES6-style modules and constructs since Moodle 3.8. These are transpiled into supported code.

This page explains the recommended way to use jQuery in core and plugins, although other older methods of including jQuery will still work these are no longer considered to be supported.

Why do we need JQuery?

info

We do not need jQuery and its use is discouraged. The following is legacy documentation and no longer current advice.

JQuery is useful for handling browser inconsistencies, and for utility functions that would otherwise be duplicated all over the code. Some particular things that JQuery is good at are:

  • DOM Manipulations
  • Promises ($.Deferred)
  • Ajax

How to use JQuery

JQuery is available via an AMD Module import and is available to all AMD JavaScript.

To make use of JQuery, either list it as a dependency of your module, or use a require call to load it.

As a dependency of a module

mod/yourplugin/amd/src/yourwidget.js
import jQuery from 'jquery';

jQuery('.example').hide();

What about JQuery UI ?

JQuery UI is a separate project containing a library of reusable widgets that relies on JQuery. JQuery UI is available for plugins to use, but it must not be used in core code.

The problems with JQuery UI are:

  • It uses an entirely different theme system for CSS that does not work well with Moodle themes
  • It introduces CSS conflicts with bootstrap
  • The widgets have some accessibility features - but only if used in a very specific way which is not well documented

Over time we will build up a library of widgets in core either by wrapping a suitable library or implementing from scratch.

If you still want to use JQuery UI in your plugin, it is available as an AMD module named jqueryui.

mod/yourplugin/amd/src/yourwidget.js
require(['jquery', 'jqueryui'], function(jQuery) {
// JQuery is available via jQuery
// JQuery UI is available via jQuery.ui
});

See also