Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Lightbox for Bootstrap 4 and jQuery
Lightbox (or "image preview") functionality for Bootstrap 4 without additional
libraries (apart from jQuery).
Written by Joaquim Homrighausen <>, 30-May-2019
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");
/* 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("", function () {
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">
<div class="modal-body text-center">
<img id="lightbox_target" class="img-fluid border border-secondary rounded" />
<div class="modal-footer">
<button type="button" tabindex="-1" id="lightbox_close" class="btn btn-primary btn-sm" data-dismiss="modal">'.
And then, to use the lightbox, you need:
<a class="xslightbox" title="Preview me"
data-title="Name of image">Preview</a>
/* At the end of a smile, there's a laugh and a half */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment