Updating Custom YUI 3 JavaScript for Moodle 2

| No Comments

In a previous entry, we wrote about how to incorporate YUI 3 JavaScript into Moodle 1.9. Recall that the advantage to using YUI 3 rather than YUI 2 or jQuery in Moodle, is that your JavaScript code is then prepped to make use of Moodle's native JavaScript framework when your courses are converted to version 2 of Moodle. Everyone visiting our Moodle 2 sites automatically download YUI 3 because of its integration with the course management system — if we make them additionally download YUI 2 or jQuery in order to experience custom interactions for our course, that adds to download size and more code for the browser to interpret, both of which can cause a more sluggish experience.

If you followed along with our previous post's Click and Tell example, or made something similar, here we'll take a look at what requires modification in your code once your course is upgraded to Moodle 2. To start with, take a look at how our references to JavaScript files looked in 1.9:

    <script type="text/javascript" src="https://moodle2.umn.edu/file.php/438/Scripts/yui3-combo.js"></script> 
    <script type="text/javascript" src="https://moodle2.umn.edu/file.php/438/Scripts/yui-click-and-tell.js"></script> 

In Moodle 2, since it already references the YUI 3 library in the head of the document, we can remove the reference to our custom implementation of YUI 3, shortening this to:

    <script type="text/javascript" src="https://moodle2.umn.edu/file.php/438/Scripts/yui-click-and-tell.js"></script> 

We'll also need to make a couple of minor adjustments in the JavaScript file itself, and in our CSS. The need for these adjustments comes from the fact that Book pages in Moodle 2 no longer have an ID of "mod-book-view" but rather "page-mod-book-view". That means that our JavaScript and CSS will not work unless we replace all instances of "mod-book-view" with "page-mod-book-view".

After you do that, your code should be good to go. The example above only directly applies to Books — if your JavaScript and CSS apply to something other than a Book, you'll need to change it accordingly. But the strategy is the same: update your JavaScript and CSS files so that they reference the new HTML structure of Moodle 2 pages, and your code should be fully functional.

Leave a comment