Create an Image modal with JavaScript!
Tags: javascript, webdev, beginners, programming
Published: 2021-12-31 11:52:48

Hi guys!

In this tutorial, we will be creating a popup image modal using javascript. The basic idea is that when a user clicks an image, a larger version should be opened in a modal. This is commonly seen in lightbox galleries and every other image gallery out there. 

Check out the detailed javascript gallery tutorials which also includes image navigation.
>[Javascript Modal Gallery](https://discover.hubpages.com/technology/javascript_gallery)

----------------------------------------------------------------

##Create a Grid of Images

Firstly, we are going to create a grid of images using CSS grid. You can create a modal using one image too, but many images is more realistic and can be used for the lightbox part too.

####HTML markup

Any images can be used for this tutorial. The HTML markup is very simple:
```html
<!DOCTYPE html>
<html lang="en">

<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script async src="https://kit.fontawesome.com/6cc05e1e8e.js" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="./style.css">
    <meta charset="UTF-8" />
</head>

<body>
    <div class="main">
        <h1>Gallery</h1>
        <div class="gallery">
            <div class="gallery__item">
                <img src="./img/1.jpg" />
            </div>
            <div class="gallery__item">
                <img src="./img/2.jpg" />
            </div>
            <div class="gallery__item">
                <img src="./img/3.jpg" />
            </div>
            <div class="gallery__item">
                <img src="./img/4.jpg" />
            </div>
            <div class="gallery__item">
                <img src="./img/5.jpg" />
            </div>
            <div class="gallery__item">
                <img src="./img/6.jpg" />
            </div>
            <div class="gallery__item">
                <img src="./img/7.jpg" />
            </div>
            <div class="gallery__item">
                <img src="./img/8.jpg" />
            </div>
        </div>
    </div>
</body>

</html>
```

You may notice a few things here. Firstly, I have imported font awesome for the icon of the close button. I have also linked the style.css, which will contain our CSS. We have 8 images, each of which are in a div called `gallery__item`.

####Styling the gallery

The CSS is quite straight forward. We are using flex box on our main container to centre everything both vertically and horizontally. Next, we are using CSS grid to created a grid of images which has 4 columns and 2 rows.
```css
* {
    padding: 0;
    margin: 0;
    box-sizing: border-box;
}

.main {
    width: 100%;
    flex-direction: column;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20px 0px 60px 0px;
}

h1 {
    margin: 10px 0px 30px 0px;
    font-family: cursive;
    color: rgb(0, 6, 90);
    font-size: 50px;
}

.gallery {
    display: grid;
    width: 90%;
    grid-template-columns: repeat(4, 1fr);
    grid-gap: 10px;
}

.gallery__item {
    cursor: pointer;
    overflow: hidden;
    border-radius: 4px;
}

.gallery__item img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: 0.3s ease-in-out;
}

.gallery__item img:hover {
    transform: scale(1.1);
}

@media (max-width: 950px) {
    .gallery {
        grid-template-columns: repeat(2, 1fr);
    }
}

@media (max-width: 550px) {
    .gallery {
        grid-template-columns: repeat(1, 1fr);
    }
}

```

Your gallery should be looking like this now:
![Browser Veiw](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x23h1zrljfmrnviwfma8.png)
 

##Javascript

Next we need to create the JS code for opening an image when clicked. Firstly, import the script:
```html
<script defer src="./script.js"></script>
```

### Getting the Image Src

Now, we need to create a function that will give us the src of the image when it is clicked. To do this, will run a `forEach` loop on all the images and store the **url** of the image is stored in the variable **imgSrc** using `e.target.src`.

```javascript
const images = document.querySelectorAll(".gallery__item img");
let imgSrc;
// get images src onclick
images.forEach((img) => {
    img.addEventListener("click", (e) => {
        imgSrc = e.target.src;
    });
});
```

### Creating the Modal and Image

Now we will create a function that will create an empty modal every time we click on an image. Here we are simply creating a div with the class _modal_.

Next, we need to create the image and add it to the modal. The src of the image will be the one we previously stored in the imgSrc variable. We will access this using a parameter.


```javascript
//creating the modal
let imgModal = (src) => {
    const modal = document.createElement("div");
    modal.setAttribute("class", "modal");
    //add the modal to the main section or the parent element
    document.querySelector(".main").append(modal);
    //adding image to modal
    const newImage = document.createElement("img");
    newImage.setAttribute("src", src);
    modal.append(newImage)
};
```


To style the modal and the image, we will use the .modal class and add the following code to the style.css.
```css
/*Image modal*/

.modal {
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: rgba(0, 0, 0, 0.733);
    margin-top: -1px;
    animation: zoom 0.3s ease-in-out;
}

@keyframes zoom {
    from {
        transform: scale(0);
    }
    to {
        transform: scale(1);
    }
}
.modal img {
    width: 50%;
    object-fit: cover;
}
```

### Creating the Close Button

Finally, we need to create a close button to close the modal. We will create the close icon using font awesome and create a simple function that will remove the modal.

```javascript
//creating the close button
const closeBtn = document.createElement("i");
closeBtn.setAttribute("class", "fas fa-times closeBtn");
//close function
closeBtn.onclick = () => {
    modal.remove();
};
modal.append(newImage, closeBtn);
```
Also style the icon:
```css
.closeBtn {
    color: rgba(255, 255, 255, 0.87);
    font-size: 25px;
    position: absolute;
    top: 0;
    right: 0;
    margin: 20px;
    cursor: pointer;
    transition: 0.2s ease-in-out;
}

.closeBtn:hover {
    color: rgb(255, 255, 255);
}
```
### Complete JS code

This is the complete javascript code.
```javascript
const images = document.querySelectorAll(".gallery__item img");
let imgSrc;
// get images src onclick
images.forEach((img) => {
    img.addEventListener("click", (e) => {
        imgSrc = e.target.src;
        //run modal function
        imgModal(imgSrc);
    });
});
//creating the modal
let imgModal = (src) => {
    const modal = document.createElement("div");
    modal.setAttribute("class", "modal");
    //add the modal to the main section or the parent element
    document.querySelector(".main").append(modal);
    //adding image to modal
    const newImage = document.createElement("img");
    newImage.setAttribute("src", src);
    //creating the close button
    const closeBtn = document.createElement("i");
    closeBtn.setAttribute("class", "fas fa-times closeBtn");
    //close function
    closeBtn.onclick = () => {
        modal.remove();
    };
    modal.append(newImage, closeBtn);
};

```

Your Gallery should be functioning like this now:

![Output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ktsjmz4867kwjyt7uhaf.gif)

And your are done!

---------------

Thank you all for reading this post!
Check out the complete JS gallery tutorial:

>[Javascript Modal Gallery](https://discover.hubpages.com/technology/javascript_gallery)

If you like my work, you can buy me a coffee and share your thoughts 🎉☕
<a href="https://www.buymeacoffee.com/salehmubashar" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/default-orange.png" alt="Buy Me A Coffee" height="41" width="174"></a>

Until next time!
Cheers! 🎉