Easy Image Preview Modal with Vanilla JavaScript — No Dependencies Required

blog
Admin
2025-06-21
1 Comments

🔔 Overview

Want to preview full-size images on click — without using jQuery, Bootstrap, or heavy libraries?

Introducing a lightweight, reusable Image Modal Preview written in pure JavaScript that:

  • Works out of the box

  • Requires zero dependencies

  • Is CDN-ready

  • Has built-in fade animations, close button, and auto-cleanup

Ideal for blogs, CMS galleries, admin dashboards, or image-driven UIs.

✨ Features

Pure JavaScript – No jQuery or libraries needed
Responsive design – Images scale to fit viewport
Click-to-preview UX with clean animation
Close by clicking outside or on "×" button
One-time style injection – Avoids CSS pollution
Modular & reusable – Use with any image by class name

⚙️ How to Use

1. Add This Script via CDN

2. Mark Images with a Class

 Preview

3. Done ✅

  Your users can now click any .view-image to see a beautiful, centered modal:

🔍 Under the Hood

The script:

  • Attaches a click listener to the entire document

  • Checks if the clicked element has .view-image

  • Extracts its src

  • Creates a modal overlay with fade-in animation

  • Injects styles only once to avoid duplicates

  • Removes itself cleanly on close

🔍 Under the Hood

The script:

  • Attaches a click listener to the entire document

  • Checks if the clicked element has .view-image

  • Extracts its src

  • Creates a modal overlay with fade-in animation

  • Injects styles only once to avoid duplicates

  • Removes itself cleanly on close

Feature This Script ✅ jQuery Lightbox ❌
No dependencies
Tiny size (<5KB) ❌ (~100KB+)
Works out of the box ⚠ Needs config
Auto CSS inject
Mobile responsive Depends

  🛠 Example Code Snippet (Click on Image below)

📣 Final Thoughts

This modal script is a plug-and-play image previewer for any modern website. No need to bloat your site with full frameworks just for simple UI behavior.

Add the class .view-image to any image, and this script does the rest — smoothly, cleanly, and fast.


© 2023 softondemand.co.in All Rights Reserved