DEV Community

MD Hasan Patwary
MD Hasan Patwary

Posted on

Building a Cute Baby Photo Gallery with Lightbox Using Pexels API

In this tutorial, we'll create a dynamic photo gallery that fetches images of cute babies from the Pexels API. The gallery will feature a responsive layout and a lightbox for viewing images in detail.

Project Demo: Live Project Link

HTML Structure

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cute Baby Photo Gallery</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="gallery" id="gallery"></div>

    <!-- Lightbox Container -->
    <div id="lightbox" class="lightbox">
        <span class="close">&times;</span>
        <img class="lightbox-content" id="lightbox-img">
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="script.js"></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

The <div id="gallery"> element serves as the container where images fetched from the Pexels API will be displayed.

The <div id="lightbox"> element is initially hidden and is used as a modal to display images in full view when clicked.

JavaScript files (jquery-3.6.0.min.js and script.js) are included at the end of the <body> for loading jQuery and our custom JavaScript functionality.

CSS Styling

#gallery {
    column-count: 4;
    column-gap: 10px;
}

@media (max-width: 575px) {
    #gallery {
        column-count: 2;
    }
}

.gallery-item {
    height: 100%;
    margin-bottom: 10px;
}

img {
    display: block;
    border-radius: 8px;
    object-fit: cover;
    width: 100%;
    height: 100%;
}

/* Lightbox overlay */
#lightbox {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.8); /* Black background with opacity */
    justify-content: center;
    align-items: center;
    z-index: 1000; /* Ensure it's on top */
}

/* Lightbox image */
#lightbox-img {
    max-width: 90%;
    max-height: 90%;
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.5); /* Slight shadow for better visibility */
}

/* Close button styling */
.close {
    position: absolute;
    top: 20px;
    right: 20px;
    color: white;
    background: rgba(0, 0, 0, 0.5);
    border: none;
    font-size: 24px;
    cursor: pointer;
    z-index: 1001; /* Ensure it's on top of the lightbox image */
}

.close:hover {
    background: rgba(0, 0, 0, 0.8);
}
Enter fullscreen mode Exit fullscreen mode

Defines the layout for the gallery (#gallery) using CSS columns, making it responsive for different screen sizes.

Each .gallery-item contains an image (img) fetched from the API, styled with border radius, object-fit, and dimensions for consistency.

The #lightbox and .close classes style the lightbox modal and its close button, providing an overlay effect (rgba(0, 0, 0, 0.8)) for better image viewing experience.

JavaScript Functionality

$(document).ready(function(){
    const apiKey = 'your_api_key_here'; // Replace with your Pexels API key
    const query = 'cute baby';
    let page = 1;
    const perPage = 50; // Adjust as needed
    const apiUrl = `https://api.pexels.com/v1/search?query=${query}&per_page=${perPage}`;

    function loadImages(page) {
        $.ajax({
            url: `${apiUrl}&page=${page}`,
            headers: {
                'Authorization': apiKey
            },
            success: function(data) {
                const photos = data.photos;
                let galleryHtml = '';

                photos.forEach(photo => {
                    galleryHtml += `
                        <div class="gallery-item">
                            <img src="${photo.src.medium}" alt="${photo.alt}">
                        </div>
                    `;
                });

                $('#gallery').append(galleryHtml);

                // Lightbox functionality
                $('.gallery-item img').click(function(){
                    $('#lightbox').css('display', 'flex');
                    $('#lightbox-img').attr('src', $(this).attr('src'));
                });

                $('.close').click(function(){
                    $('#lightbox').hide();
                });

                $('#lightbox').click(function(event) {
                    if(event.target.id === 'lightbox') {
                        $('#lightbox').hide();
                    }
                });
            },
            error: function() {
                alert('Failed to fetch images from Pexels API.');
            }
        });
    }

    // Initial load
    loadImages(page);

    // Infinite scroll
    $(window).scroll(function() {
        if($(window).scrollTop() + $(window).height() >= $(document).height() - 100) {
            page++;
            loadImages(page);
        }
    });
});
Enter fullscreen mode Exit fullscreen mode

Uses jQuery ($(document).ready(function(){ ... });`) to ensure the DOM is fully loaded before executing any code.

apiKey, query, page, perPage, and apiUrl variables are defined to interact with the Pexels API.

loadImages(page) function makes an AJAX request to fetch images based on the search query ('cute baby') and pagination (page).
On successful API response (success: function(data) { ... }), iterates through data.photos to generate HTML (galleryHtml) for each image fetched, appending it to #gallery.

Enables lightbox functionality: when an image is clicked, displays the #lightbox modal (display: flex) and sets the #lightbox-img source to the clicked image's source.
Provides a close button (.close) and click outside #lightbox functionality to hide the lightbox modal.

Implements infinite scroll: when the user scrolls near the bottom of the page ($(window).scroll(function() { ... })), increments page and loads more images using loadImages(page).

Conclusion

This project combines HTML, CSS, and JavaScript to create a modern and interactive photo gallery with a lightbox feature, fetching images from the Pexels API. Each part of the code plays a crucial role in creating a responsive and visually appealing photo gallery experience.

Feel free to customize the project further based on your requirements and design preferences. Enjoy building your own dynamic photo galleries with API integration!

Top comments (0)