Enhancing Page Elements with Moodle and JavaScript

Exclusive offer: get 50% off this eBook here
Moodle JavaScript Cookbook

Moodle JavaScript Cookbook — Save 50%

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

£14.99    £7.50
by Alastair Hole | May 2011 | Cookbooks Moodle Open Source Web Development

The Yahoo! UI Library (YUI) offers a range of widgets and utilities to bring modern enhancements to your traditional Moodle page elements. In this article, we will look at a selection of these, including features often seen on modern interactive interfaces such as auto-complete, auto-update, custom tooltips, and so on.

In this article by Alastair Hole, author of Moodle JavaScript Cookbook, we will cover:

  • Adding a text box and combo box with auto-complete
  • Displaying auto-updating data
  • Enabling resizable elements
  • Adding custom tooltips and button controls

 

Moodle JavaScript Cookbook

Moodle JavaScript Cookbook

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

        Read more about this book      

(For more resources on this subject, see here.)

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:

<?php
require_once(dirname(__FILE__) . '/../config.php');
$PAGE->set_context(get_context_instance(CONTEXT_SYSTEM));
$PAGE->set_url('/cook/autocomplete.php');
$PAGE->requires->js('/cook/autocomplete.js', true);
?>
<?php
echo $OUTPUT->header();
?>
<div style="width:15em;height:10em;">
<input id="txtInput" type="text">
<div id="txtInput_container"></div>
</div>
<?php
echo $OUTPUT->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:

<div style="width:15em;height:10em;">
<input id="txtCombo" type="text" style="vertical-align:top;
position:static;width:11em;"><span id="toggle"></span>
<div id="txtCombo_container"></div>
</div>

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:"&darr;"});
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.

 

Moodle JavaScript Cookbook Over 50 recipes for making your Moodle system more dynamic and responsive with JavaScript
Published: April 2011
eBook Price: £14.99
Book Price: £24.99
See more
Select your format and quantity:
        Read more about this book      

(For more resources on this subject, see here.)

Displaying auto-updating data

Another useful interface enhancement is the ability to display data that is constantly updated at a set timed interval. For example, this could be used to update a list of news headlines every five minutes, or update the display of live stock data every minute.

In this recipe, we will take the basic example of a clock, displaying the full date and time on the page, and update it every second using the polling extension to the DataSource utility. This technique can be used to display any data from any data source, and update it as frequently as we like.

How to do it...

In this example, we will set up a very simple PHP page, autoupdate.php, containing only one placeholder div in which we will display the current date and time:

<?php
require_once(dirname(__FILE__) . '/../config.php');
$PAGE->set_context(get_context_instance(CONTEXT_SYSTEM));
$PAGE->set_url('/cook/autoupdate.php');
$PAGE->requires->js('/cook/autoupdate.js', true);
echo $OUTPUT->header();
?>
<div id="txtUpdate"></div>
<?php
echo $OUTPUT->footer();
?>

Next, we define the associated JavaScript in autoupdate.js:

YUI().use("datasource-function", "datasource-polling", function(Y) {
var getDateString = function()
{
return new Date();
};
var dataSource = new Y.DataSource.Function({source:getDateString});
var request =
{
callback :
{
success: function(e)
{
document.getElementById('txtUpdate').innerHTML =
e.response.results[0];
}
}
};
var id = dataSource.setInterval(1000,request);
});

We have prepared a container element in the HTML in which to display the data.

We then define a DataSource object to use as the source of the data we will display. In this example, we used a Function data source, that is, a data source which simply uses the output of a native JavaScript function as its data (in this case, the current date and time). Once again, this data source can be substituted for any valid YUI data source, such as, a CSV of stock information or an RSS feed of news headlines.

Next, we define a request callback handler, which is used to display the data.

Finally, we register this handler with the DataSource object and configure it to poll (update) this data source every second (1,000 milliseconds).

How it works...

We have loaded two YUI modules: datasource-function and datasource-polling.

The first allows us to use a native JavaScript function as a DataSource, the second allows us to get the DataSource to update or 'poll' for new data as often as we specify.

The function data source we have defined simply returns the current date and time, and the callback handler simply writes the output into our container element.

All that is left is to use the setInterval method of the DataSource to register the defined callback function, and to configure it to update every 1,000 milliseconds (1 second).

We now see, upon loading the page, that the full current date and time is displayed, and updated every second, effectively creating a text based clock on the page, as shown in the following screenshot:

Enhancing Page Elements with Moodle and JavaScript

Enabling resizable elements

Another simple, but effective YUI2 utility is the resize utility. It has myriad uses from the simple (in this example, allowing a block of text to be resizable), to the more complicated scenarios (such as resizable form elements). It allows a user to change the size of the element in question by just dragging resize handles around the page, similar to how the user would resize any application window in an operating system's GUI. This is most useful when the element contains a large amount of content, allowing the user to size the element as required.

How to do it...

To begin, set up a simple page, resize.php with a block of text in a containing element, as follows:

<?php
require_once(dirname(__FILE__) . '/../config.php');
$PAGE->set_context(get_context_instance(CONTEXT_SYSTEM));
$PAGE->set_url('/cook/resize.php');
$PAGE->requires->js('/cook/resize.js', true);
?>
<?php
echo $OUTPUT->header();
?>
<div id="content" style="width:20em;padding:1em;">
<p>
Moodle (abbreviation for Modular Object-Oriented Dynamic Learning
Environment) is a
free and open-source e-learning software platform, also known as a
Course Management System,
Learning Management System, or Virtual Learning Environment (VLE).
As of October 2010 it had a user base of 49,952 registered and
verified sites, serving 37 million users in 3.7 million
courses.</p>
</div>
<?php
echo $OUTPUT->footer();
?>

The associated JavaScript resize.js is very simple:

YUI().use("yui2-resize", function(Y) {
var YAHOO = Y.YUI2;
var resize = new YAHOO.util.Resize("content");
});

Instantiate a new Resize object, and pass the name of the element to make resizable as the only argument.

This allows the element to be resizable in both axes, with resize handles on the right and bottom of the element as seen in the following screenshot:

Enhancing Page Elements with Moodle and JavaScript

How it works...

Instantiating the Resize control and passing the element to enhance in the constructor causes YUI to add resize handles to the element which allows it to be resized horizontally and vertically.

Adding custom tooltips

HTML tooltips, set up through the title attributes of elements, allow only text-based tooltips with no control over the layout. In this example, we will enhance an existing element with the YUI Tooltip widget.

How to do it...

To begin, set up a PHP page, tooltip.php, containing an image with the title attribute set:

<?php
require_once(dirname(__FILE__) . '/../config.php');
$PAGE->set_context(get_context_instance(CONTEXT_SYSTEM));
$PAGE->set_url('/cook/tooltip.php');
$PAGE->requires->js('/cook/tooltip.js', true);
echo $OUTPUT->header();
?>
<img id="logo" src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="../theme/image.php?theme=standard&image=moodlelo
go" title="Moodle Logo" />
<?php
echo $OUTPUT->footer();
?>

Next, set up the associated JavaScript file tooltip.js:

YUI().use("yui2-yahoo-dom-event", "yui2-animation", "yui2-container",
function(Y) {
var YAHOO = Y.YUI2;
var toolTip = new YAHOO.widget.Tooltip("toolTip", {
context: "logo"});
});

Create an element to which we will add a custom tooltip. In this example, we have only used an img tag with the title attribute set. Instantiate a new Tooltip widget, and pass the following two arguments:

  1. The name of the tooltip object.
  2. A configuration object, with the context property set to the name of the element to enhance.

How it works...

YUI "progressively enhances" the specified element by adding a custom tooltip element containing the original title text. Now when we hover over the image element to which we added the custom tooltip, we see the enhanced version appear, as shown in the following screenshot:

Enhancing Page Elements with Moodle and JavaScript

Adding custom button controls

YUI has a Button widget control, which offers many features for enhancing standard HTML button controls. It allows a great level of control over the look and function of the button, such as adding images, or allowing the button to have a label that differs from its value. In this example, we will enhance a basic HTML input button.

How to do it...

To begin, set up a PHP page, button.php, with an HTML input button control:

<?php
require_once(dirname(__FILE__) . '/../config.php');
$PAGE->set_context(get_context_instance(CONTEXT_SYSTEM));
$PAGE->set_url('/cook/button.php');
$PAGE->requires->js('/cook/button.js', true);
?>
<?php
echo $OUTPUT->header();
?>
<input id="btnButton" type="button" value="Custom Button" />
<?php
echo $OUTPUT->footer();
?>

Next, define the associate JavaScript file button.js:

YUI().use("yui2-button", function(Y) {
var YAHOO = Y.YUI2;
var customButton = new YAHOO.widget.Button("btnButton");
});

Instantiate a new Button widget control, and pass the ID of the button to enhance as the only argument. This then replaces the original element with a custom, skinned HTML button control that can now be customized further, as shown in the following screenshot:

Enhancing Page Elements with Moodle and JavaScript

How it works...

The original HTML input button is replaced in the DOM by YUI with an HTML button control, wrapped in a placeholder span element. This can now be skinned or further enhanced with YUI button widget features.

Summary

In this aryticle we saw how to use the Yahoo! UI Library (YUI) widgets and utilities to bring modern enhancements to your traditional Moodle page elements.


Further resources on this subject:


Moodle JavaScript Cookbook Over 50 recipes for making your Moodle system more dynamic and responsive with JavaScript
Published: April 2011
eBook Price: £14.99
Book Price: £24.99
See more
Select your format and quantity:

About the Author :


Alastair Hole

Alastair Hole is a web software developer, currently specializing in educational software—particularly that which pertains to Further and Higher Education in the UK. His web development experience began in the post dot-com boom era, working on business-to-business e-commerce web applications in the publishing industry with a focus on back-office integration. He has since then transferred his talents to the educational sector, and has created projects that have gone on to receive awards from bodies such as The Times Educational Supplement and the IMS Global Learning Consortium.

Alastair is the author of the award-winning Moodle IMS Content Package repository plugin 'MrCUTE - Moodle Repository: Create, Upload, Tag & Embed' [http://www.mrcute.co.uk] which is an Open Source project commissioned by the Joint Information Systems Committee (JISC) that has seen significant usage in Moodle sites worldwide, from Scotland to Australia.

Alastair maintains an interest in free and open educational software, and is currently involved in a number of bids for JISC funding to further develop repositories to provide easy access to learning materials in the UK Further and Higher Education sectors.

Books From Packt


Object-Oriented JavaScript
Object-Oriented JavaScript

Moodle Security
Moodle Security

Moodle 1.9 for Design and Technology
Moodle 1.9 for Design and Technology

Moodle 2.0 for Business Beginner's Guide
Moodle 2.0 for Business Beginner's Guide

Moodle 2.0 Multimedia Cookbook: RAW
Moodle 2.0 Multimedia Cookbook: RAW

Moodle 1.9 Top Extensions Cookbook
Moodle 1.9 Top Extensions Cookbook

Moodle 1.9 Theme Design: Beginner's Guide
Moodle 1.9 Theme Design: Beginner's Guide

Moodle as a Curriculum and Information Management System
Moodle as a Curriculum and Information Management System


Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software