7 min read

 

Moodle JavaScript Cookbook

Moodle JavaScript Cookbook

Over 50 recipes for making your Moodle system more dynamic and responsive with JavaScript

Introduction

The Yahoo! UI Library (YUI) offers a range of widgets and utilities to bring modern enhancements to your traditional page elements. In this chapter, we will look at a selection of these enhancements, including features often seen on modern interactive interfaces, such as:


  • Auto-complete: This feature suggests possible values to the user by searching against a list of suggestions as they start typing. We will look at two different ways of using this. First, by providing suggestions as the user types into a text box, and second, by providing a list of possible values for them to select from a combo list box.
  • Auto-update: This technique will allow us to update an area of the page based on a timed interval, which has many uses as we’ll see. In this example, we will look at how to create a clock by updating the time on the page at one second intervals. This technique could also be used, for example, to update a news feed every minute, or update stock information every hour.
  • Resizable elements: A simple enhancement which allows users to dynamically resize elements to suit their needs. This could be applied to elements containing a significant amount of text which would allow the user to control the width of the text to suit their personal preference for ideal readability.
  • Custom tooltips: Tooltips appear when an element is hovered, displaying the associated title or alternative text (that is, a description of an image or the title of a hyperlink). This enhancement allows us to have more control over the look of the tooltips making them more visually appealing and more consistent with the overall look and feel of our page.
  • Custom buttons: This enhancement allows us to completely restyle button elements, modifying their look and feel to be consistent with the rest of our page. This also allows us to have a consistent button style across different platforms and web browsers.

We will once again be using mostly YUI Version 2 widgets and utilities within the YUI Version 3 framework. At the time of writing, few YUI2 widgets have been ported to YUI3. This method allows us the convenience of the improvements afforded by the YUI3 environment combined with the features of the widgets from YUI2.

Adding a text box with auto-complete

A common feature of many web forms is the ability to provide suggestions as the user types, based on a list of possible values. In this example, we enhance a standard HTML input text element with this feature.

This technique is useful in situations where we simply wish to offer suggestions to the user that they may or may not choose to select, that is, suggesting existing tags to be applied to a new blog post. They can either select a suggested value that matches one they have started typing, or simply continue typing a new, unused tag.

How to do it…

First, set up a basic Moodle page in the usual way. In this example, we create autocomplete. php with the following content:

set_context(get_context_instance(CONTEXT_SYSTEM));
 $PAGE->set_url('/cook/autocomplete.php');
 $PAGE->requires->js('/cook/autocomplete.js', true);
 ?>
 header();
 ?>
 
footer(); ?>

Secondly, we need to create our associated JavaScript file, autocomplete.js, with the following code:

YUI().use("yui2-autocomplete", "yui2-datasource", function(Y) {
 var YAHOO = Y.YUI2;
 var dataSource = new YAHOO.util.LocalDataSource
 (
 ["Alpha","Bravo","Beta","Gamma","Golf"]
 );
 var autoCompleteText = new YAHOO.widget.AutoComplete("txtInput",
 "txtInput_container", dataSource);
 });

How it works…

Our HTML consists of three elements, a parent div element, and the other two elements contained within it: an input text box, and a placeholder div element to use to display the auto-complete suggestions.

Our JavaScript file then defines a DataSource to be used to provide suggestions, and then creates a new AutoComplete widget based on the HTML elements we have already defined.

In this example, we used a LocalDataSource for simplicity, but this may be substituted for any valid DataSource object.

Once we have a DataSource object available, we instantiate a new YUI2 AutoComplete widget, passing the following arguments:

  • The name of the HTML input text element for which to provide auto-complete suggestions
  • The name of the container element to use to display suggestions
  • A valid data source object to use to find suggestions

Now when the user starts typing into the text box, any matching auto-complete suggestions are displayed and can be selected, as shown in the following screenshot:

Enhancing Page Elements with Moodle and JavaScript

Adding a combo box with auto-complete

In this example, we will use auto-complete in conjunction with a combo box (drop-down list). This differs from the previous example in one significant way—it includes a drop-down arrow button that allows the user to see the complete list of values without typing first.

This is useful in situations where the user may be unsure of a suitable value. In this case, they can click the drop-down button to see suggestions without having to start guessing as they type. Additionally, this method also supports the same match-as-you-type style auto-complete as that of the previous recipe.

How to do it…

Open the autocomplete. php file from the previous recipe for editing, and add the following HTML below the text box based auto-complete control:

Next, open the JavaScript file autocomplete.js, and modify it to match the following code:

YUI().use("yui2-autocomplete", "yui2-datasource", "yui2-element",
 "yui2-button", "yui2-yahoo-dom-event", function(Y) {

var YAHOO = Y.YUI2;

var dataSource = new YAHOO.util.LocalDataSource
(
["Alpha","Bravo","Beta","Gamma","Golf"]
);
var autoCompleteText = new YAHOO.widget.AutoComplete("txtInput",
"txtInput_container", dataSource);
var autoCompleteCombo = new YAHOO.widget.AutoComplete("txtCombo",
"txtCombo_container", dataSource, {minQueryLength: 0,
queryDelay: 0});
var toggler = YAHOO.util.Dom.get("toggle");
var tButton = new YAHOO.widget.Button({container:toggler,
label:"↓"});
var toggle = function(e) {
if(autoCompleteCombo.isContainerOpen()) {
autoCompleteCombo.collapseContainer();
}
else {
autoCompleteCombo.getInputEl().focus();
setTimeout(function() {
autoCompleteCombo.sendQuery("");
},0);
}
}
tButton.on("click", toggle);
});

You will notice that the HTML we added in this recipe is very similar to the last, with the exception that we included a span element just after the text box. This is used as a placeholder to insert a YUI2 button control.

This recipe is somewhat more complicated than the previous one, so we included some extra YUI2 modules: element, button, and yahoo-dom-event.

We define the AutoComplete widget in the same way as before, except we need to add two configuration options in an object passed as the fourth argument.

Next, we retrieve a reference to the button placeholder, and instantiate a new Button widget to use as the combo box ‘drop-down’ button.

Finally, we define a click handler for the button, and register it.

We now see the list of suggestions, which can be displayed by clicking on the drop-down button, as shown in the following screenshot:

Enhancing Page Elements with Moodle and JavaScript

How it works…

The user can type into the box to receive auto-complete suggestions as before, but may now use the combo box style drop-down button instead to see a list of suggestions.

When the user clicks the drop-down button, the click event is fired.

This click event does the following:

  • Hides the drop-down menu if it is displayed, which allows the user to toggle this list display on/off.
  • If it is not displayed, it sets the focus to the text box (to allow the user to continue typing), and execute a blank query on the auto-complete widget, which will display the list of suggestions. Note that we explicitly enabled this blank query earlier when we defined the AutoComplete widget with the “minQueryLength: 0” option, which allowed queries of length 0 and above.

 

LEAVE A REPLY

Please enter your comment!
Please enter your name here