H5P Guides

Using other libraries

In this tutorial, we will show you how to use other H5P libraries in your custom library.

Using other libraries is a powerful feature of H5P. In this tutorial, we will add a task to our example to show how easy it is to use already existing libraries in another library.

Update your semantics

First we need to describe which libraries may be used. This is done in our library's semantics.json where we add the following:

{
  "name": "task",
  "type": "library",
  "label": "Task",
  "options": [
    "H5P.MultiChoice 1.7",
    "H5P.Blanks 1.6"
  ]
}

Make sure you use the right version numbers for MultiChoice and Blanks. In the time of writing the latest stable versions are 1.7 and 1.6, but you have to use versions you have installed on your system. H5P can keep several versions of a library on the system so you don't have to update your library when libraries you use are updated. Your library will keep using the specified versions until you update your library.

Important to notice here is type (which is set to library) and the options array. Read more about semantics here.

Invoke and resize the task libraries

The H5P core will not initialize the external libraries – this must be done by our library. To do this, use the H5P.newRunnable() function, which will return a new instance. Also make sure the new library gets to respond to any resize events. Add the following to your constructor: 

if (this.options.task) {
  // Initialize task
  this.task = H5P.newRunnable(this.options.task, this.id);

  // Trigger resize events on the task:
  this.on('resize', function (event) {
    this.task.trigger('resize', event);
  });
}

To append the library to the DOM, invoke the attach function. Add the following to your attach function:

if (this.task) {
  // Create a container for the task
  var $taskHolder = $('<div>');

  // Attach the task to the container
  this.task.attach($taskHolder);

  // Append the task container to our content types container
  $container.append($taskHolder);
}

It is important to notice that the first parameter in H5P.newRunnable is the field exemplified in the semantics above. As a rule of thumb, we initialize the other library in our constructor and attach it to the DOM in our attach function.

Override CSS

When including external libraries you often need context dependent styling. In the example below we override the background color of the buttons in the task:

/* Task buttons override */
.h5p-greetingcard .h5p-joubelui-button {
  background-color: #000000;
}

To be able to override a library's CSS, we need to use a more specific CSS selector than the library already is using. Please don't use the !important rule, since this is considered bad practice.

The complete code is attached.