Front-End Development Building an Image Upload Feature with JavaScript Mastering Image Alignment: Centering Images with HTML & CSS Adding Video to Your React Native App with react-native-video HTML Image Slider: Do It Yourself and 1-Step Image Gallery Widget How to Effectively Manage Digital Assets in a PHP Image Gallery Introducing Angular Image Editor: Your New Editing Too Mastering Javascript Image Annotation Mastering JavaScript Image Popup Python Video Player: 3 Free Options and a Quick Tutorial Image Recognition Machine Learning: Use Cases and Common Algorithms HTML/CSS: How to Center Images Vertically and Horizontally How to Create an Image Map Understand CSS Background Position with 4 Simple Examples Java for Image Processing: 4 Libraries You Should Know Python Video Processing: 6 Useful Libraries and a Quick Tutorial Blur Image CSS: Two Ways to Blur Images for Gorgeous Effects Designing a Video Flipping App for Android Build an App for Embedding Video Watermarks on Android Devices Change Image on Hover with HTML and CSS How to Align Images with CSS Full Page Background Image with CSS: Tutorial and 5 Automation Tips Using CSS to Scale Page Elements and a Better Way to Scale Your Images CSS Background Image: Quick Tutorial and 3 Automation Tips Featured Image: Best Practices to Feature Images on Your Website Image Gallery Websites: Tips and Tricks for a Stunning Image Gallery 6 Ways to Stretch a Background Image with CSS Auto Cropping for Images and Video: Features & Best Practices FLAC vs. WAV: 4 Key Differences and How to Choose Converting Audio to Video: A Practical Guide FLAC vs. AIFF: 5 Key Differences and How to Choose FLAC vs. MQA: 5 Key Differences and How to Choose Converting WAV Files To OGG The Ultimate Guide On Converting OGG Files To WAV Sound Choices: FLAC vs. MP3 AAC vs MP3 – The Future of Audio Files All about AIFF and how it compares to WAV and MP3 Integrating Cloudinary with Netlify Integrating Cloudinary with Svelte and SvelteKit Integrating Cloudinary with Nuxt Integrating Cloudinary with Gatsby File Upload as a Service: How It Works and 5 Leading Solutions Native Mobile App Development Creative Uses for CSS Inner Border and 3 Ways to Set a Border Integrating Cloudinary with Next.js Front-End Development: The Complete Guide

Mastering JavaScript Image Popup

javascript image popup

We all know that stunning visuals can significantly boost your reach. But simply displaying images isn’t enough. JavaScript image popups offer a dynamic way to present visuals, boosting user engagement and providing a more immersive experience.

In this article, we’ll learn about crafting these popups using the potent combination of JavaScript and Cloudinary. We’ll explore the key steps involved, from integrating Cloudinary’s image delivery features to leveraging JavaScript’s capabilities for a developer-friendly approach to creating exceptional image popups.

In this article:

javascript image popup

Implementing Image Popup Using JavaScript

Before we begin creating popup images using JavaScript, ensure you have a basic understanding of HTML and JavaScript. Familiarity with HTML structures will allow you to create the visual elements of the popup. At the same time, a grasp of JavaScript fundamentals like event listeners will enable you to control when and how the popup appears and disappears.

For this tutorial, we will host our assets on Cloudinary. This will help us deliver responsive images that are compatible with every screen type. To do this, we must create a Cloudinary account, so head on over and sign up for free.

Setting up Cloudinary

Now that we’ve covered the essentials, let’s prepare our images for upload. Cloudinary provides two upload methods: the Cloudinary Console and API calls. In this article, we’ll use the user-friendly Cloudinary Media Console for image uploads.

First, log in to your account to upload images using Cloudinary’s website. Once logged in, you’ll be on the Media Library Dashboard. There, look for an Upload button and click it:

javascript image popup

Next, click the Browse button to select the files you want to upload.

javascript image popup

Verify your uploads by navigating to the Assets tab, which shows all your assets on the cloud.

javascript image popup

Once you’ve uploaded your assets, open your image in the Cloudinary console and add your image tags. This will help us retrieve multiple images of the same tag when we populate our Image Popup app.

javascript image popup

HTML Structure for Our Page

With the setup now complete, we can begin creating the front end of our app. We will begin by creating a simple HTML page that will display all the images in a specific tag, with the public ID under each image.

To do this, we will first create a standard HTML document declaration and define the language.

<!DOCTYPE html>
<html lang="en">

<head>
</head>

<body>
</body>

</html>

Next, for the <head> section, we will define the page title and add our external style and script sheet (we will discuss this later), which will hold the styling and functionality for the pop-up behavior.

Finally, for the body of our HTML page, we will begin by adding a <header> tag that will hold the website’s title displayed within a <div> element with a class of "container". This class will be defined in an external stylesheet later.

...
<body>
    <header>
        <div class="container">
            <h1>My Photos</h1>
        </div>
    </header>
...

After the header, we create a <main> tag containing a div element belonging to the container class. This contains an unordered list with the class "images" and ID "imageList" created. This will be used to display our images dynamically populated using Javascript.

<body>
    <header>
        <div class="container">
            <h1>My Photos</h1>
        </div>
    </header>
    <main>
        <div class="container">
            <ul class="images" id="imageList">
                <!-- Images will be added here dynamically -->
            </ul>
        </div>
    </main>
...

Finally, we will define a hidden element with the ID "myModal" and the class "modal". This represents the pop-up window that will appear when an image is clicked. A closing button is placed inside the modal, along with an image element with the ID "img01" and class "modal-content". This is where the enlarged image will be displayed. A <div> with the ID "caption" is also included to display information about the image. Here is what our final HTML page looks like:

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Cloudinary Pop-up Images</title>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
</head>

<body>
    <header>
        <div class="container">
            <h1>My Photos</h1>
        </div>
    </header>
    <main>
        <div class="container">
            <ul class="images" id="imageList">
                <!-- Images will be added here dynamically -->
            </ul>
        </div>
    </main>
    <div id="myModal" class="modal">
        <span class="close">x</span>
        <img class="modal-content" id="img01">
        <div id="caption"></div>
    </div>
</body>

</html>

JavaScript Code for Image Popup

Now that our HTML is complete, we can begin coding our Popup app. To do this, we will start by creating a new JS file called script.json in the same directory as our HTML.

We will begin by defining a window.onload() function that will initialize our HTML page. Here, we will start by defining some variables for our Cloudinary cloud name and tag and construct a Cloudinary URL that retrieves a JSON object containing the URLs of all images of a particular tag.

window.onload = function () {
    var images = [];

    // Replace 'demo' and 'logo' with your cloud name and tag
    
    var cloudName = 'your_cloud_name';
    var tag = 'project';

    // URL to fetch images from Cloudinary
    
    var url = 'https://res.cloudinary.com/' + cloudName + '/image/list/' + tag + '.json';

Next, we will define a fetch function inside the onload function that uses the URL to retrieve the JSON data containing image information from Cloudinary.

   fetch(url)
        .then(response => response.json())
        .then(data => {
            // Loop through each image

            data.resources.forEach(image => {
                var imageUrl = 'https://res.cloudinary.com/' + cloudName + '/image/upload/' + image.public_id + '.' + image.format;

                // Add image to array

                images.push({ src: imageUrl, title: image.public_id });
            });

            // Call the function to load images

            loadImages(images);
        })
        .catch(error => console.error('Error:', error));

Here, we wrap our function in the .then() method to handle the successful response, converting it to JSON using .json(). The inner .then() loop iterates through each image in the data.resources array. Finally, inside the loop, we create an image URL for each image and then push an object with src (image URL) and title (image public ID) to the images array.

Next, we define our loadImages() function as follows:

    // Function to create and append the list items


function loadImages(imageArray) {
        // Get the list element from the HTML.

        const list = document.getElementById('imageList');

        // Loop through each image in the array.

        imageArray.forEach((image, index) => {

            // Create a new list item for each image.

            const listItem = document.createElement('li');

            // Set a key attribute for the list item using the image title, converted to lowercase.

            listItem.setAttribute('key', image.title.toLowerCase());

            // Create a div to hold the image.

            const imageDiv = document.createElement('div');

            // Add a class to the div for styling purposes.

            imageDiv.className = 'imageImage';

            // Create an img element for the image and set attributes.

            const img = document.createElement('img');
            img.src = image.src;
            img.alt = image.title;

            // Create a h3 element for the image title and set attributes.

            const title = document.createElement('h3');
            title.className = 'imageTitle';
            title.textContent = image.title;

            // Append the img element to the imageDiv.

            imageDiv.appendChild(img);

            // Append the imageDiv and title to the listItem.

            listItem.appendChild(imageDiv);
            listItem.appendChild(title);

            // Append the listItem to the list.

            list.appendChild(listItem);

            // Add click event to the imageDiv

            imageDiv.onclick = function () {
                modal.style.display = "block";
                modalImg.src = img.src;
                captionText.innerHTML = title.textContent;
            }
        });
    }

The loadImages function takes in an imageArray as input. It retrieves the imageList element using document.getElementById(). It then iterates through each image object in the imageArray. Inside the loop, we create a new <li> element for each image list item and assign a key attribute to the <li> element using the image title for efficient identification. We then create a <div> element to hold the image and style using className.

Next, we make an <img> element; its src attribute is set to the image URL, and an alt attribute with the image title is added for accessibility. We then create a <h3> element for the image title and style using className. Each image is then appended to the image container <div>, which is then appended to the list item and the title. The list item is then the image list (ul). Finally, an event listener (click event) is added to each image container <div>, which, when clicked, sets the modal element’s display style to “block” to show it, changes modalImg‘s src attribute to the clicked image’s URL and finally changes the captionText‘s inner HTML to the clicked image’s title.

With the loadImages function now complete, we retrieve references to the modal (modal), image (modalImg), caption (captionText), and close button (span). We then add an onlick function to the span, which, when clicked, sets the modal’s display style is set to "none" to hide it. Here is what our complete JS file looks like:

window.onload = function () {
    var images = [];

    // Replace 'demo' and 'logo' with your cloud name and tag
    var cloudName = 'your_cloud_name';
    var tag = 'project';

    // URL to fetch images from Cloudinary
    var url = 'https://res.cloudinary.com/' + cloudName + '/image/list/' + tag + '.json';

        fetch(url)
            .then(response => response.json())
            .then(data => {
                // Loop through each image
                data.resources.forEach(image => {
                    var imageUrl = 'https://res.cloudinary.com/' + cloudName + '/image/upload/' + image.public_id + '.' + image.format;

                    // Add image to array
                    images.push({ src: imageUrl, title: image.public_id });
                });

                // Call the function to load images
                loadImages(images);
            })
            .catch(error => console.error('Error:', error));

    // Function to create and append the list items
    function loadImages(imageArray) {
        // Get the list element from the HTML.
        const list = document.getElementById('imageList');

        // Loop through each image in the array.
        imageArray.forEach((image, index) => {
            // Create a new list item for each image.
            const listItem = document.createElement('li');
            // Set a key attribute for the list item using the image title, converted to lowercase.
            listItem.setAttribute('key', image.title.toLowerCase());

            // Create a div to hold the image.
            const imageDiv = document.createElement('div');
            // Add a class to the div for styling purposes.
            imageDiv.className = 'imageImage';

            // Create an img element for the image and set attributes.
            const img = document.createElement('img');
            img.src = image.src;
            img.alt = image.title;

            // Create a h3 element for the image title and set attributes.
            const title = document.createElement('h3');
            title.className = 'imageTitle';
            title.textContent = image.title;

            // Append the img element to the imageDiv.
            imageDiv.appendChild(img);
            // Append the imageDiv and title to the listItem.
            listItem.appendChild(imageDiv);
            listItem.appendChild(title);

            // Append the listItem to the list.
            list.appendChild(listItem);

            // Add click event to the imageDiv
            imageDiv.onclick = function () {
                modal.style.display = "block";
                modalImg.src = img.src;
                captionText.innerHTML = title.textContent;
            }
        });
    }

    // Get the modal
    var modal = document.getElementById("myModal");

    // Get the image and insert it inside the modal
    var modalImg = document.getElementById("img01");
    var captionText = document.getElementById("caption");

    // Get the <span> element that closes the modal
    var span = document.getElementsByClassName("close")[0];

    // When the user clicks on <span> (x), close the modal
    span.onclick = function () {
        modal.style.display = "none";
    }
}

Now that our JS is complete, all we need to do is create a style.css file to add some style to our Image Popup app. Here is what our CSS file looks like:

* {
        box-sizing: border-box;
        margin: 0;
    }


    body {
        padding: 0;
        width: 100%;
        min-height: 100vh;
        display: grid;
        grid-template-rows: auto 1fr;
        justify-content: center;
        background: #111827;
        color: #fff;
    }


    img {
        max-width: 100%;
        height: auto;
        transition: all .2s ease-in-out;
        opacity: 1;
    }


    img:hover {
        transform: scale(1.2);
        opacity: 0.8;
        border: 5px solid #0f3897;
    }


    a {
        color: inherit;
    }


    header {
        padding: 1em 0;
        margin-bottom: .5em;
        font-size: 1em;
        font-weight: 500;
        margin: 0;
    }


    header>div {
        display: flex;
        flex-direction: column;
        align-items: center;
    }


    .container {
        width: 100%;
        max-width: 1024px;
        padding: 0 1em;
        margin: 0 auto;
    }


    .images {
        list-style: none;
        padding: 0;
        margin: 1em;
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
        grid-gap: 3em;
    }


    .imageTitle {
        font-size: 1.4em;
        margin: .4em 0 0;
    }


    .modal {
      display: none; /* Hidden by default */
      position: fixed; /* Stay in place */
      z-index: 1; /* Sit on top */
      padding-top: 100px; /* Location of the box */
      left: 0;
      top: 0;
      width: 100%; /* Full width */
      height: 100%; /* Full height */
      overflow: auto; /* Enable scroll if needed */
      background-color: rgb(0,0,0); /* Fallback color */
      background-color: rgba(0,0,0,0.9); /* Black w/ opacity */
    }


    /* Modal Content (image) */
    .modal-content {
      margin: auto;
      display: block;
      width: 80%;
      max-width: 700px;
    }


    /* Caption of Modal Image */
    #caption {
      margin: auto;
      display: block;
      width: 80%;
      max-width: 700px;
      text-align: center;
      color: #ccc;
      padding: 10px 0;
      height: 150px;
    }


    /* Add Animation */
    .modal-content, #caption {
      animation-name: zoom;
      animation-duration: 0.6s;
    }


    @keyframes zoom {
      from {transform:scale(0)}
      to {transform:scale(1)}
    }


    /* The Close Button */
    .close {
      position: absolute;
      top: 15px;
      right: 35px;
      color: #f1f1f1;
      font-size: 40px;
      font-weight: bold;
      transition: 0.3s;
    }


    .close:hover,
    .close:focus {
      color: #bbb;
      text-decoration: none;
      cursor: pointer;
    }

Finally, all we need to do is to open our HTML page. Here is what our app looks like:

javascript image popup

Hovering on an image highlights the outline of the image and expands it by a small factor.

javascript image popup

Finally, clicking on an image expands it to occupy the entire screen, with its title displayed on the button and a close button on the top-right corner.

javascript image popup

Wrapping Up

As we wrap up this tutorial, remember that user engagement hinges on thoughtful design and seamless interactions. Cloudinary empowers developers and content creators to deliver attractive images without compromising performance. Whether you’re a beginner or an experienced developer, integrating Cloudinary into your projects will elevate your media management game.

This cloud-based media management platform simplifies handling images, videos, and other rich media assets. Integrating Cloudinary’s features allows you to manage, optimize, and display images across devices.

Transform your digital asset management with Cloudinary’s seamless image and video optimization today! Sign up for free today!

More from Cloudinary:

Automated JavaScript Image Transformation and Management

Cloudinary as the server-side for Javascript image cropping libraries

QUICK TIPS
Colby Fayock
Cloudinary Logo Colby Fayock

In my experience, here are tips that can help you better master JavaScript image popups:

  1. Preload images for smooth popups
    To avoid delays when images are loaded into a popup, preload the images when the page loads. This ensures that when a user clicks on an image, it appears instantly.
  2. Optimize image size dynamically based on viewport
    Utilize Cloudinary’s responsive breakpoints to dynamically adjust the image size based on the user’s screen resolution. This minimizes load times and ensures that images look sharp without being unnecessarily large.
  3. Add touch event listeners for mobile users
    Enhance the user experience on touch devices by adding touch event listeners in addition to click events. This allows for a more natural interaction on smartphones and tablets.
  4. Implement lazy loading for image lists
    If you have a large number of images, consider using lazy loading to load images only as they come into the user’s view. This reduces the initial load time and improves performance, especially on slower networks.
  5. Include image fallback for non-JS environments
    Consider providing a fallback for users who have JavaScript disabled. For example, allow the images to display in a new tab or directly on the page without the popup effect.
  6. Debounce scroll and resize events
    If your popup or image loading logic is dependent on scrolling or resizing, debounce these events to prevent performance bottlenecks. This ensures smoother user interactions without lag.
  7. Use CSS transitions for smoother animations
    Enhance the visual appeal of your popups by implementing CSS transitions for the opening and closing animations. This provides a more polished experience compared to immediate changes in opacity or size.
  8. Utilize ARIA roles for better accessibility
    Improve the accessibility of your popups by adding ARIA roles and labels to describe the popup content. This helps screen readers interpret the modal and its controls correctly.
  9. Prevent scroll bleed through the background
    When a modal is open, prevent the background content from being scrollable. This can be achieved by adding a body { overflow: hidden; } style when the popup is active, ensuring the focus remains on the modal content.
  10. Implement keyboard navigation for modals
    Support keyboard accessibility by allowing users to close the modal with the Escape key and navigate through images with the arrow keys. This is essential for users who rely on keyboard navigation.
Last updated: Aug 24, 2024