Using jQuery with Moodle
Having just been helping someone with a jQuery integration I thought I would document the simple process of including the jQuery library within a theme, block, or module and how to make use of it.
jQuery support in Moodle 2.5
Moodle 2.5 contains jQuery and JQuery UI libraries in default installation, see jQuery for more developer documentation.
Before we begin
note: This is for Moodle versions before 2.5, please see jQuery doc for 2.5 onwards.
I can't guarantee what you are doing will work nicely next to YUI, but hopefully it will!
So first up, make sure you get the latest jQuery files from http://docs.jquery.com/Downloading_jQuery. For the purposes of this document I have downloaded jquery-1.4.2.min.js.
Including jQuery within a plugin
Themes are not the easiest type of plugin to include jQuery, but if you are working on an installation that will be using a lot of customised code, then probably it is the best place.
- Open the themes config.php in your favourite editor (Notepad)
You should end up with the following directory structure:
And the following entry in your themes config.php file:
// Remember we don't put the file extension so no .js at the end
And with that jQuery is now being loaded within your theme!
However you won't see it immediately, first you need to clear Moodles theme cache. This can be done is two ways when logged in as an Admin:
- Site Administration > Appearance > Themes > Theme selector. At the top of the page will be a button to invalidate the theme cache.
- Site Administration > Appearance > Themes > Theme settings. Turn on Theme Designer Mode.
Blocks and modules
This is much simplier than including jQuery from within a theme.
- Add the following lines of php into every file which will make use of jQuery.
And that's it, it is served within the footer of those pages.
If you want to include jQuery within the page header however you will need to specify true as the second argument.
You should be aware that jQuery is only designed to be included within a page once, unfortunately you are the controller of this and will need to ensure it complies.
If you are writing customisations for your own site then it is not a problem, you can either include it within your theme once (and know it will be everywhere), or you can move the files to a central location (e.g. moodle/lib/jquery/*) and then include them from there using the block and module syntax.
If however you are using third party plugins, where more than one is making use of jQuery, you may find VERY strange things happening. You will either need to remove the modules or move the jQuery files to a central location, as above, edit the plugins to find the files there.
Note: A file within one location will only be included once within a page.
For these reasons it is HIGHLY recommended to use YUI for everything possible.
- Themes 2.0