SyntaxStudy
Sign Up
jQuery Intermediate 5 min read

Image Lightbox

Lightbox

Build a lightbox that opens full-size images in an overlay with keyboard navigation.

Example
const $lb = $("<div>").attr("id","lightbox").html("<img id='lb-img'><button id='lb-close'>&times;</button>").appendTo("body").hide();
$(".gallery img").on("click", function() {
  $("#lb-img").attr("src", $(this).data("full") || this.src);
  $lb.fadeIn(200);
  $("body").css("overflow","hidden");
});
$("#lb-close, #lightbox").on("click", function(e) {
  if (e.target === this) { $lb.fadeOut(200); $("body").css("overflow",""); }
});
$(document).on("keydown", e => { if (e.key === "Escape") $("#lb-close").trigger("click"); });
Pro Tip

Trap focus inside the lightbox and restore it to the triggering image on close for accessibility.