Created
May 31, 2019 05:29
-
-
Save joho1968/4b86e638f9967d95ec43780277fb3d58 to your computer and use it in GitHub Desktop.
Lightbox for Bootstrap 4 and jQuery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
=== | |
Lightbox (or "image preview") functionality for Bootstrap 4 without additional | |
libraries (apart from jQuery). | |
Written by Joaquim Homrighausen <[email protected]>, 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> | |
/* 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