Selecting a photo from a collection and displaying several images on a single page

I'm looking for a way to enhance my image gallery by clicking on each image to reveal 4 related images without the need to create separate pages for each one. Any suggestions on how to achieve this efficiently?

Currently, I am utilizing an image gallery from: http://codepen.io/dimsemenov/pen/ZYbPJM

Although I've used Adobe InDesign to display four images in one PNG file due to space constraints, I believe there are more visually appealing and practical solutions available. Please advise.

<!DOCTYPE html>
<html >
<head>
  <meta charset="UTF-8">
  <title>Imgur Results</title>

  <link rel='stylesheet prefetch' href='https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.1/photoswipe.min.css'>
<link rel='stylesheet prefetch' href='https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.1/default-skin/default-skin.min.css'>

      <link rel="stylesheet" href="css/style.css">


</head>

<body>
  <h2>Banana:</h2>

  <div class="my-gallery" itemscope itemtype="http://schema.org/ImageGallery">

    <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
      <a href="imgur/banana/banana1.png" itemprop="contentUrl" data-size="900x900">

          <img  src="imgur/banana/3NlNsLB.jpg" itemprop="thumbnail" alt="Image description"  />

      </a>

    </figure>



    <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
      <a href="imgur/banana/banana2.tif" itemprop="contentUrl" data-size="900x900">
          <img src="imgur/banana/6gqpgDV.jpg" itemprop="thumbnail" alt="Image description" />
      </a>
    </figure>

https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.1/photoswipe.min.js'>

<script src="js/index.js"></script>

This is the JavaScript code:

var initPhotoSwipeFromDOM = function(gallerySelector) {

    // extracting slide data (url, title, size ...) from DOM elements 
    // (children of gallerySelector)
    var parseThumbnailElements = function(el) {
        var thumbElements = el.childNodes,
            numNodes = thumbElements.length,
            items = [],
            figureEl,
            linkEl,
            size,
            item;

        for(var i = 0; i < numNodes; i++) {

            figureEl = thumbElements[i]; // <figure> element

            if(figureEl.nodeType !== 1) {
                continue;
            }

            linkEl = figureEl.children[0]; // <a> element

            size = linkEl.getAttribute('data-size').split('x');

            item = {
                src: linkEl.getAttribute('href'),
                w: parseInt(size[0], 10),
                h: parseInt(size[1], 10)
            };



            if(figureEl.children.length > 1) {
                item.title = figureEl.children[1].innerHTML; 
            }

            if(linkEl.children.length > 0) {
                item.msrc = linkEl.children[0].getAttribute('src');
            } 

            item.el = figureEl; 
            items.push(item);
        }

        return items;
    };

    var closest = function closest(el, fn) {
        return el && ( fn(el) ? el : closest(el.parentNode, fn) );
    };

    var onThumbnailsClick = function(e) {
        e = e || window.event;
        e.preventDefault ? e.preventDefault() : e.returnValue = false;

        var eTarget = e.target || e.srcElement;

        var clickedListItem = closest(eTarget, function(el) {
            return (el.tagName && el.tagName.toUpperCase() === 'FIGURE');
        });

        if(!clickedListItem) {
            return;
        }

        var clickedGallery = clickedListItem.parentNode,
            childNodes = clickedListItem.parentNode.childNodes,
            numChildNodes = childNodes.length,
            nodeIndex = 0,
            index;

        for (var i = 0; i < numChildNodes; i++) {
            if(childNodes[i].nodeType !== 1) { 
                continue; 
            }

            if(childNodes[i] === clickedListItem) {
                index = nodeIndex;
                break;
            }
            nodeIndex++;
        }



        if(index >= 0) {
            openPhotoSwipe( index, clickedGallery );
        }
        return false;
    };

    var photoswipeParseHash = function() {
        var hash = window.location.hash.substring(1),
        params = {};

        if(hash.length < 5) {
            return params;
        }

        var vars = hash.split('&');
        for (var i = 0; i < vars.length; i++) {
            if(!vars[i]) {
                continue;
            }
            var pair = vars[i].split('=');  
            if(pair.length < 2) {
                continue;
            }           
            params[pair[0]] = pair[1];
        }

        if(params.gid) {
            params.gid = parseInt(params.gid, 10);
        }

        return params;
    };

    var openPhotoSwipe = function(index, galleryElement, disableAnimation, fromURL) {
        var pswpElement = document.querySelectorAll('.pswp')[0],
            gallery,
            options,
            items;

        items = parseThumbnailElements(galleryElement);

        options = {

            galleryUID: galleryElement.getAttribute('data-pswp-uid'),

            getThumbBoundsFn: function(index) {
                var thumbnail = items[index].el.getElementsByTagName('img')[0], 
                    pageYScroll = window.pageYOffset || document.documentElement.scrollTop,
                    rect = thumbnail.getBoundingClientRect(); 

                return {x:rect.left, y:rect.top + pageYScroll, w:rect.width};
            }

        };

        if(fromURL) {
            if(options.galleryPIDs) {
                for(var j = 0; j < items.length; j++) {
                    if(items[j].pid == index) {
                        options.index = j;
                        break;
                    }
                }
            } else {
                options.index = parseInt(index, 10) - 1;
            }
        } else {
            options.index = parseInt(index, 10);
        }

        if( isNaN(options.index) ) {
            return;
        }

        if(disableAnimation) {
            options.showAnimationDuration = 0;
        }

        gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
        gallery.init();
    };

    var galleryElements = document.querySelectorAll( gallerySelector );

    for(var i = 0, l = galleryElements.length; i < l; i++) {
        galleryElements[i].setAttribute('data-pswp-uid', i+1);
        galleryElements[i].onclick = onThumbnailsClick;
    }

    var hashData = photoswipeParseHash();
    if(hashData.pid && hashData.gid) {
        openPhotoSwipe( hashData.pid ,  galleryElements[ hashData.gid - 1 ], true, true );
    }
};

initPhotoSwipeFromDOM('.my-gallery');

This is the CSS:

.my-gallery {
  width: 100%;
  float: left;
}

.my-gallery img {
  width: 200px;
  height: 200px;
  display: block;
}
.my-gallery figure {
  display: block;
  float: left;
  margin: 0px 15px 20px 0;
  border: 3px solid #000;

}

.my-gallery figcaption {
  display: none;
}

Is there a simpler method to create this image gallery without relying on the aforementioned library?

I aim to achieve a design similar to this when clicking on an image: https://i.sstatic.net/gPZdS.png ^ The above design was created with Adobe Illustrator but it would be great to replicate it using HTML/CSS.

Here's how the gallery appears: https://i.sstatic.net/BZP62.png

Answer №1

One way to accomplish this is by utilizing Fancybox and its features.

Take a look at this Fiddle for reference.

In the provided example, when you click on a visible image, it triggers an event that reveals a hidden gallery using Fancybox.

Here is the HTML code:

<!-- Visible image(s) -->
    <a class="fancyboxLauncher" href="http://fancyapps.com/fancybox/demo/1_b.jpg" title="one"><img src="http://fancyapps.com/fancybox/demo/1_s.jpg" alt="" /></a>

<!-- Hidden gallery -->    
    <div style="display: none;">
    <a class="fancybox" href="http://farm4.staticflickr.com/3712/9032543579_1217e6566b_b.jpg" title="one"></a>

<a class="fancybox" href="http://farm4.staticflickr.com/3818/9036037912_83576fe5ab_b.jpg" title="two"></a>

And here is the JavaScript code:

// Event trigger
$(".fancyboxLauncher").on("click", function () {
    $(".fancybox").eq(0).trigger("click");
    return false;
});

// Initialize Fancybox
$(".fancybox")
    .attr('rel', 'gallery')
    .fancybox({
    padding: 0
});

You are not limited to using only a 4-in-1 image – feel free to experiment with different options!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unleashing the power of RollupJs: A guide to dynamically bundling modules and objects

Is there a way to dynamically bundle a module/object into my RollupJs output file? I have experimented with various options without success in achieving the desired result. Below is a brief sample project that demonstrates what I am trying to achieve. The ...

Error: Missing Required Parameter for PUT Request

I'm encountering an error while trying to execute a PUT request. { "error" : { "status" : 400, "message" : "Required parameter position_ms missing" } } I have consistently used the same format for all previous PUT requests, and everythi ...

Combining CSS and JavaScript to handle two events with a single onClick

Here is the code I've created: <a href="#" id="home" class="showLink" onclick="showHide('example');return false;"> <li class="buttons">home</li> </a> <a href="#" id="user" class="showLink" onclick="showHide(&a ...

Code breaking due to Selenium locating element by class

When my application opens a login page, it looks for valid combinations. Initially, there is a button labeled as "check availability" that Selenium can locate and click on. If the username is already taken, a new button appears with the text "check anothe ...

One potential solution is sending a message to a user via a server using JavaScript on Node.js

Hey there, I've encountered a minor issue and would appreciate your help. Recently, I developed a weather program in NodeJs where users can search for the weather in their city. However, I'm facing a challenge with displaying the weather data to ...

The dirtyVertices feature in Three.js seems to be malfunctioning

In my three.js project, I created a 12*12 plane and attempted to modify its vertices between two renderings without success. Despite adding the following code, no changes were observed: ground.geometry.dynamic = true; ground.geometry.__dirtyVertices = tr ...

The progress bar in jQuery seems to be malfunctioning

I encountered an issue with the jQuery progress bar where it only displays [object Object]% instead of showing the actual progress. I have tried using jQuery library and CSS, but it is not rendering correctly on my page. How can I fix this? I am consider ...

Deleting a Form using Jquery Post Submission (JSP and Servlet)

Is there a way to submit multiple forms using Jquery and remove them from the list after submission? Here's an example of my JSP code: <form action="searchTweet" method="post"> <textarea name="searchTxt"></textarea> <inpu ...

The website's navigation system effectively directs content within the initial 100% viewport

I have encountered a slight issue. I created a Sidebar Navigation with some added "hey's" to demonstrate the problem: * { margin: 0; padding: 0; font-family: 'Roboto', sans-serif; } nav { height: 100vh; width: 250px; borde ...

Ways to transfer data from PHP to JavaScript

I have three separate files that contain different functionalities: functions.php (contains all functions for the database) main.html (my main program) main.js (includes all javascript functions) Currently, I am looking to call a PHP function using AJAX ...

How can I set an object as a variable in JavaScript (specifically React) based on two different conditions?

const router = useRouter(); const { locale } = router; const featureId = props.id; let featureContent; featureContent = locale === "en" ? featureContentEn : locale === "de" ? featureContentDe : lo ...

Exploring the possibilities of integrating ajax results with pagination

Throughout my extensive experience in development, there's one concept that has always puzzled me - how to properly implement pagination with AJAX search results. For instance, I have 40 search results and I'd like to display them in groups of 1 ...

The d3.js circles mysteriously disappear when attempting to implement the update pattern

I find myself in a challenging situation once again - there may come a day when I am the one offering help, but for now, I admit that I am feeling quite lost. I am very new to d3.js and my understanding of JavaScript is still quite basic. My current proje ...

Execute the script only if the designated object is present on the page

A few years ago, I wrote some JavaScript code that is now causing errors to pop up in the console on pages where the object it relies on is not present. The error messages look like this... Cannot read property 'top' of undefined TypeError: Ca ...

The styling of section and small elements appears differently in Internet Explorer compared to Chrome

I am working on an HTML code to showcase a list of individuals, including their names and statuses. <section class="box-time"> <ul class="group"> <li> <a class="fancybox fancybox.ajax" href="../loadFancybox.php ...

Conclusion of Tour when an event is triggered by the parent view - Intro.js

File Manager - Home Normal https://i.stack.imgur.com/7C5lH.png I primarily utilize AJAX callbacks for most of my content. Whenever I click a link button on the page, it triggers a modal pop-up using jQuery events and a specific class. The Tour Guide implem ...

Traverse an SVG element using JavaScript

I have a beautiful star SVG that I created, and I want to use it instead of styling a span to create floating bubbles in my div. However, I'm facing some challenges in adapting my Javascript loop to incorporate the SVG for creating the bubbles, as opp ...

Having trouble with $.ajax? I can't seem to get it to hit my controller action. Can anyone provide

Seeking assistance. I need help with the following code snippet: <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <script type="text/javascript> function GOTO() { var datastring = "id=2"; $. ...

Tips for rearranging a span following an image?

Looking for a solution to rearrange a span element after an image within automatically generated HTML. Sample HTML: <span>closed</span> <img alt="Click to reset" src="xxx" class=""> Currently, the span appears before the img in the cod ...

Guide to attaching and displaying an image on a Three.js map

Currently, I have a 3D map loaded with three.js that includes mouse interaction. I've managed to place an image on the map using absolute positioning, but unfortunately, as I move the map around, the image stays stationary. Does anyone know how I can ...