Wednesday, March 6, 2013

Include javascript file in your theme

Including javascript inside my moodle theme gave me soooo much headache.
Now I've finally figured out how to do it, and this post will be my proof!

1)  Go inside your "/theme/mythemename"   folder. If you don't have one already, create a new folder called "javascript."


2)  Inside the new javascript folder, upload or create your actual javascript file. We could call it "text.js" for example purposes. 

3) Next, go inside your  "theme/mythemename/config.php."  At the very bottom of the file, we will add a new line of code to include your javascript file. 
$THEME->javascripts_footer = array('test');  // Recommended:  This loads the file in the html footer

OR you could load the file in the html header:
$THEME->javascripts = array('test');

4)  In order to see the changes, the caches of the site must be purged. What I normally do:
-- Turn on "Theme designer mode" while I'm working, to automatically prevent caching
-- Go to "Admin -> Development -> Purge all caches" (if not in designer mode)
-- Refresh the page you want to see

Just a word of warning:  jQuery does funky things to Moodle and half of the time, including it will give you more headache than not. Try to use the YUI libraries and find equivalent functions instead of jQuery.

Here is the offical documentation from Moodle about jQuery and including javascript files:

5 comments:

  1. Also works:
    $THEME->javascripts[] = 'test';
    It adds a JS file to an array of others if there are any.

    ReplyDelete
  2. Thanks a lot for sharing. Our qualified and experienced development team has changed and included additional features to the already existing Canvas layout to rename it as Customize Canvas LMS. If you need any help from us email at: info@cryptextechnologies.com

    ReplyDelete
  3. It always strikes me how incomplete the moodle documentation is. Simple tasks such as include your JS is an issue and it takes a good 15 min of googling to find the answer.

    Thanks you for the post.

    ReplyDelete