Unlayer Examples
Documentation

Custom Media Library

In this example, we will use our custom media library for image selection.

We will be using Bootstrap and jQuery in this example for Modals.


Media Library Modal

Let's start by adding the HTML for our media library modal.

<div id="mediaLibrary" class="modal" tabindex="-1" role="dialog">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">My Media Library</h5>
        <button
          type="button"
          class="close"
          data-dismiss="modal"
          aria-label="Close"
        >
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <p>Choose an image</p>
        <div class="images">
          <div class="image">
            <img src="https://picsum.photos/id/1/800" />
          </div>

          <div class="image">
            <img src="https://picsum.photos/id/10/800" />
          </div>

          <div class="image">
            <img src="https://picsum.photos/id/20/800" />
          </div>

          <div class="image">
            <img src="https://picsum.photos/id/30/800" />
          </div>

          <div class="image">
            <img src="https://picsum.photos/id/40/800" />
          </div>

          <div class="image">
            <img src="https://picsum.photos/id/50/800" />
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

JavaScript

We will initialize the editor first.

unlayer.init({
  id: 'editor',
  displayMode: 'email',
});

Next, we'll add the selectImage callback. This callback is triggered when user clicks Upload Image button.

We will open our media library modal when a user clicks Upload Image. The important thing to notice here is the done callback function. When a user selects an image from your media library, you will need to pass the URL to the done callback function.

unlayer.registerCallback('selectImage', function (data, done) {
  // Open the modal
  $('#mediaLibrary').modal();

  $('#mediaLibrary .images img').bind('click', function (e) {
    // User has clicked on an image
    // This is where we will call Unlayer's "done" callback function
    // We will pass the image URL so Unlayer knows what image is added
    done({ url: $(e.target).attr('src') });

    // Close the modal
    $('#mediaLibrary').modal('hide');
  });
});

// We will unbind any previous image click events when modal opens to avoid duplicate events
$(document).ready(function () {
  $('#mediaLibrary').on('show.bs.modal', function () {
    $('#mediaLibrary .images img').unbind('click');
  });
});

Live Demo

Here's a live preview of our custom media library.

  • Drag the "Image" tool and drop it on the canvas
  • Click "Upload Image" to try our new media library