A simple, lightweight (10kb unminified), and mobile-friendly pure JavaScript lightbox to show images in a popup box with a close button. This vanilla JavaScript lightbox plugin doesn’t require any external framework or library to work.
Code Features
- Easy to initialize.
- Responsive, fully mobile friendly.
- Debounced launch, default 500ms, the customs rate can be set with rate property of options object.
- A preloading spinner that is unset after onload event succeeds.
- Pure CSS Retina Ready UI images.
- Custom event callback functions.
How to Create a Pure JavaScript Lightbox
1. Include the img-lightbox
‘s CSS and JavaScript files into your HTML document to create an image lightbox.
<!-- Lightbox CSS --> <link rel="stylesheet" href="css/img-lightbox.css"> <!-- Lightbox JavaScript --> <script src="js/img-lightbox.js"></script>
2. Create markup for your images as follows. Wrap your image in the anchor link of the full-width image and insert the thumbnail URL in img
src.
<a href="https://farm1.staticflickr.com/955/27854475488_5f82a379ca_z.jpg" class="img-lightbox-link" aria-hidden="true" rel="lightbox"> <img src="https://farm1.staticflickr.com/955/27854475488_5f82a379ca_z.jpg" alt="Image Lightbox" /> </a>
3. Finally, initialize the img-lightbox
plugin in HTML <script>
tag with all available options.
(function (root) { "use strict"; if (root.imgLightbox) { imgLightbox("img-lightbox-link", { onCreated: function () { /* show your preloader */ }, onLoaded: function () { /* hide your preloader */ }, onError: function () { /* hide your preloader */ }, onClosed: function () { /* hide your preloader */ }, rate: 500 /* default: 500 */ , touch: false /* default: false - use with care for responsive images in links on vertical mobile screens */ }); } })("undefined" !== typeof window ? window : this);
That’s all! hopefully, you have successfully created an image lightbox. If you have any questions or facing any issues, feel free to comment below.
Similar Code Snippets:
I code and create web elements for amazing people around the world. I like work with new people. New people new Experiences.
I truly enjoy what I’m doing, which makes me more passionate about web development and coding. I am always ready to do challenging tasks whether it is about creating a custom CMS from scratch or customizing an existing system.