H5P Guides

jQuery usage and integration

This page describes H5P usage of jQuery.

After reading, you will know:

  • how to use jQuery in your H5P code
  • what tweaks have been done to base jQuery UI
  • how to include other jQuery extensions in H5P

H5P.jQuery

H5P includes jQuery natively but includes it in the H5P global object. From here it can be accessed as H5P.jQuery. This is done to prevent namespace collisions, and to ensure a reasonably up-to-date version of jQuery is always available, regardless of what the hosting site includes.

The included version is jQuery 1.9. This means that H5P libraries should avoid older jQuery functions obsoleted from this version. See the jQuery 1.9 upgrade guide for information on changed functionality from older versions.

How to wrap jQuery extensions in an H5P library

Other jQuery extensions may be included directly in your library or by defining a separate library for it and including this as a dependency. The latter is preferred as it allows for reusability in other libraries.

To create a jQuery extension library, you need to make the library extend the H5P.jQuery object, rather than the global jQuery or $ objects. For well-written jQuery plugins, this should be as simple as replacing the invocation function parameter jQuery with H5P.jQuery like this modified version of the sample from jQuery docs.

(function ( $ ) {
    var shade = "#556b2f";
    $.fn.greenify = function() {
        this.css( "color", shade );
        return this;
    };

// Normal invocation
// }( jQuery ));

// H5P version
}( H5P.jQuery ));

For very complex libraries (like jQuery UI) that includes many such invocations, add the following code at the top and bottom of the extension Javascript files.

// Add to the top of the javascript file.
var __oldJQuery = jQuery;
jQuery = H5P.jQuery;

//
// jQuery extension code goes here. Remember to keep license information
// and other file intro comments.
//

// Add to the end of the javascript file.
jQuery = __oldJQuery;

Tweaks to jQuery UI

jQuery UI is not included natively in H5P but is available as an H5P library that may be included as a dependency in your H5P library. The library injects it in the H5P.jQuery object, and from there it can be used as normal. jQuery UI Touch Punch is also included to enable touch event support for mobile devices.

Define the dependency in your library's library.json file as below. The sample is taken from the H5P.DragQuestion library, that uses the jQuery UI draggable/droppable interface. To see it in action, take a look at the Drag question demo.

  "preloadedDependencies": [
    {
      "machineName": "jQuery.ui",
      "majorVersion": 1,
      "minorVersion": 10,
      "defaultStyles": true
    }
  ],