Lightbox for Bootstrap 4 and jQuery

Lightbox (or “image preview”) functionality for Bootstrap 4 without additional libraries (apart from jQuery).

Written by Joaquim Homrighausen <joho@webbplatsen.se>
30-May-2019
TEAMYUJO

Do as you wish with this 🙂

This is the Javascript/jQuery code for the Bootstrap 4 modal. You don’t have to use jQuery to accomplish this obviously.

$(document).ready(function($) {

  $(".xslightbox").click(function () {
    if ($(this).attr("data-message") != "undefined") {
      document.getElementById("lightbox_target").src = "";
      document.getElementById("lightbox_target").src = $(this).attr("data-message");
    }
    if ($(this).attr("data-title") != "undefined") {
      document.getElementById("lightbox_title").innerText = $(this).attr("data-title");
      }
    $("#xslightmodal").modal("show");
  });
  /* This will focus the close button, but you don't really need to do this or
     have a close button for that matter since Bootstrap will close the modal
     if you click outside the modal or - in this case - press the Esc key */
  $("#xslightmodal").on("shown.bs.modal", function () {
    $("#lightbox_close").trigger("focus");
  });

});

This is the HTML for the Bootstrap 4 modal. You can style it any which way you want. The key to getting the image to behave as you want it (i.e. to make the image responsive) is adding the “img-fluid” class to the img tag.

You can add the “fade” class to the modal if you want it to be “animated”.

<div class="modal" id="xslightmodal" tabindex="-1" role="dialog" aria-hidden="true" data-keyboard="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content bg-light">
      <div class="modal-header">
        <div class="modal-title text-lowercase text-monospace small" id="lightbox_title">
          placeholder
        </div>
      </div>
      <div class="modal-body text-center">
        <img id="lightbox_target" class="img-fluid border border-secondary rounded" />
      </div>
      <div class="modal-footer">
        <button type="button" tabindex="-1" id="lightbox_close" class="btn btn-primary btn-sm" data-dismiss="modal">'.
          Close
        </button>
      </div>
    </div>
  </div>
</div>

And then, to use the lightbox, you need:

<a class="xslightbox" title="Preview me"
   data-message="https://url/to/image/or/loader/script"
   data-title="Name of image">Preview</a>

This is also available as a gist on GitHub. Knock yourself out 🙂

Leave a Comment

Notify me of followup comments via e-mail. You can also subscribe without commenting.