Javascript

jQuery Lightbox: A Pop-up Image Viewer

jQuery Lightbox: Pop-up Image Viewer

✅ Features:

  • Click thumbnail → Show large image in overlay

  • Dark background (modal style)

  • Close on background click or X button


HTML Structure

html
<!-- Image Thumbnails -->
<div class="gallery">
<img src="thumb1.jpg" data-full="large1.jpg" alt="Image 1" />
<img src="thumb2.jpg" data-full="large2.jpg" alt="Image 2" />
<img src="thumb3.jpg" data-full="large3.jpg" alt="Image 3" />
</div>

<!-- Lightbox -->
<div id="lightbox">
<span class="close">&times;</span>
<img id="lightbox-img" src="" alt="Full Image" />
</div>

<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>


CSS Styling

html
<style>
.gallery img {
width: 100px;
margin: 10px;
cursor: pointer;
border-radius: 4px;
}

#lightbox {
display: none;
position: fixed;
z-index: 999;
top: 0; left: 0;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.8);
justify-content: center;
align-items: center;
}

#lightbox img {
max-width: 90%;
max-height: 80%;
border-radius: 6px;
}

#lightbox .close {
position: absolute;
top: 30px;
right: 40px;
color: white;
font-size: 2rem;
font-weight: bold;
cursor: pointer;
}
</style>


⚙️ jQuery Script

js
$(document).ready(function () {
$('.gallery img').click(function () {
const fullImg = $(this).data('full');
$('#lightbox-img').attr('src', fullImg);
$('#lightbox').fadeIn();
});

// Close on click outside image or on close button
$('#lightbox, .close').click(function (e) {
if (e.target !== $('#lightbox-img')[0]) {
$('#lightbox').fadeOut();
}
});
});


How It Works:

  1. Each thumbnail <img> contains a data-full attribute with the full-size image.

  2. When clicked, the lightbox opens and displays that image.

  3. Clicking outside the image or on the close button hides the lightbox.


✅ Optional Enhancements:

  • Add arrow buttons to navigate next/prev

  • Add keyboard controls (←/→/ESC)

  • Add captions or zoom functionality

  • Make it responsive for mobile

Leave a Reply

Your email address will not be published. Required fields are marked *