Rearrange the order of items in the fancybox gallery

Typically, fancybox displays items in the gallery based on the order they are added in the HTML code.

Is there a way to customize the order of items when they are opened in the popup, while keeping the original order when displayed on the page?

The solution involves adding a optional data- attribute to each item:

<a class="fancybox" rel="gallery1" href="http://farm2.staticflickr.com/1617/24108587812_6c9825d0da_b.jpg" title="Morning Godafoss (Brads5)">
    <img src="http://farm2.staticflickr.com/1617/24108587812_6c9825d0da_m.jpg" alt="" />
</a>
<a class="fancybox" rel="gallery1" href="http://farm4.staticflickr.com/3691/10185053775_701272da37_b.jpg" title="Vertical - Special Edition! (cedarsphoto)">
    <img src="http://farm4.staticflickr.com/3691/10185053775_701272da37_m.jpg" alt="" />
</a>
<a class="fancybox" rel="gallery1" href="http://farm1.staticflickr.com/574/22407305427_69cc6e845f_b.jpg" title="Racing against the Protons (tom.leuzi)">
    <img src="http://farm1.staticflickr.com/574/22407305427_69cc6e845f_m.jpg" alt="" />
</a>
<a class="fancybox" rel="gallery1" href="http://farm1.staticflickr.com/291/18653638823_a86b58523c_b.jpg" title="Lupines (Kiddi Einars)">
    <img src="http://farm1.staticflickr.com/291/18653638823_a86b58523c_m.jpg" alt="" />
</a>

JavaScript code for fancybox initialization:

$(".fancybox").fancybox();

JSFiddle

If you want to open the images in the popup in a different order than they appear on the page, you can use the following setup:

Specify the desired order using the data-fancybox-order attribute like this:

<a class="fancybox" rel="gallery1" data-fancybox-order="3" ... >
<a class="fancybox" rel="gallery1" data-fancybox-order="1" ... >
<a class="fancybox" rel="gallery1" data-fancybox-order="4" ... >
<a class="fancybox" rel="gallery1" data-fancybox-order="2" ... >

With this setup, navigation buttons will adjust based on the specified order. For example, if the second image is clicked (data-fancybox-order="1"), there will be no previous button. Clicking next will open the fourth image, then the first, and finally the third image (data-fancybox-order="4"), after which the next button will disappear.

What's the best approach to implement this?

Answer №1

Regrettably, fancybox does not provide an option for that specific feature. It may be necessary to manually create and initiate the fancybox gallery in the desired sequence.

To achieve this, you must assign a data attribute to each html element to specify the display order within the fancybox gallery. For instance:

<a class="fancybox" href="image03.jpg" title="title 3" data-order="3">...
<a class="fancybox" href="image01.jpg" title="title 1" data-order="1">...
<a class="fancybox" href="image04.jpg" title="title 4" data-order="4">...
<a class="fancybox" href="image02.jpg" title="title 2" data-order="2">...

As the gallery will be constructed programmatically, the rel attribute becomes redundant.

Instead of utilizing the standard fancybox initialization script $(".fancybox").fancybox(), you need to bind a click event to dynamically create and launch the fancybox gallery:

$(".fancybox").click(function(){
    // establish the fancybox gallery here
    return false; // prevent default event behavior and propagation
});

Upon clicking any of the html thumbnails, the process involves:

  • obtaining the index of the clicked image (data-order attribute)
  • collecting all html elements with class fancybox (querySelectorAll())
  • initializing the array of elements for the fancybox gallery
  • iterating through the html elements and adding them to the fancybox gallery array
  • sorting the fancybox array

Since the fancybox gallery object will consist of an array of objects, a function is required to sort such an array based on a chosen property. This function can be sourced from this answer:

// function to sort array of objects by a property
var sortObjectsBy = function(field, reverse, primer) {
  var key = primer ? function(x) {
    return primer(x[field])
  } : function(x) {
    return x[field]
  };
  reverse = !reverse ? 1 : -1;
  return function(a, b) {
    return a = key(a),
      b = key(b),
      reverse * ((a > b) - (b > a));
  }
}

Subsequently, all components are integrated after the click event:

$(".fancybox").on("click", function() {
  // retrieve the index of the clicked image
  var thisIndex = this.dataset.order - 1;
  // gather all html elements
  var elements = document.querySelectorAll(".fancybox");
  // initialize the array for the fancybox gallery
  var fancyElements = [];
  // include the html elements in the fancybox gallery
  for (var i = 0, elLength = elements.length; i < elLength; i++) {
    fancyElements.push({
      href: elements[i].href,
      title: elements[i].title + " - " + elements[i].dataset.order,
      order: elements[i].dataset.order
    });
  }
  // sort the fancybox array of objects by the "order" property
  fancyElements.sort(sortObjectsBy("order", false, function(a) {
    return a;
  }));
  // programmatically launch fancybox
  $.fancybox(fancyElements, {
    helpers: {
      title: {
        type: "inside"
      }
    },
    // specify starting index
    index: thisIndex // commence gallery from the selected element
  })
  return false;
});

You have the flexibility to incorporate additional fancybox options into the script, similar to the inclusion of the title type. Moreover, the addition of the order to the title serves illustrative purposes to validate the orderly presentation determined by the data-order attribute.

Moreover, while the order property is non-essential for fancybox functionality, it facilitates sorting the array effectively.

Refer to JSFIDDLE for further details.

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

Selenium is not designed for scraping images

I'm currently working on a web scraping project in Python using Selenium to extract images from a website. I've encountered some difficulties in locating the image elements within the webpage. Here's the code snippet I'm using: driver ...

Placing text in a box in the corner while maintaining the ability to scroll

I'm looking for a solution to wrap text around a toolbox while keeping the total height limited and allowing the text to scroll. The challenge is to have the corner box stay fixed in the corner without scrolling along with the text. How can I achieve ...

Getting HTML from Next.js middleware - a step-by-step guide

Is there a way to send the HTTP Status Code 410 (gone) together with a customized HTML message? I want to display the following content: <h1>Error 410</h1> <h2>Permanently deleted or Gone</h2> <p>This page is not foun ...

Is it possible to utilize the output of a function nested within a method in a different method?

I am currently facing a challenge with my constructor function. It is supposed to return several methods, but I'm having trouble using the value from this section of code: var info = JSON.parse(xhr.responseText); Specifically, I can't figure ou ...

Modifying Ajax-injected HTML with JQuery's editInPlace functionality

I have been successfully using the JQuery editInPlace plug-in on a static HTML page. However, I am facing an issue when trying to use the same plugin with HTML injected via an Ajax call. I have heard that using .on() like '$('.edit_inplace_fiel ...

Automatically forward after submitting the form

I am utilizing the Mingle plugin on my Wordpress website to allow users to register and post on a dedicated Mingle Forum. Although the signup process is functioning correctly, I wish to enhance user experience by redirecting them to the forum page after t ...

Routing with nested modules in Angular 2 can be achieved by using the same

Encountering a common issue within a backend application. Various resources can be accessed through the following routes: reports/view/:id campains/view/:id suts/view/:id certifications/view/:id Note that all routes end with the same part: /view/:id. ...

Navigating with React Router Dom and parsing objects in search parameters

Currently, I am utilizing React Router Dom v6 and require the ability to retain object search parameters within the URL. My current approach involves: const [searchParams, setSearchParams] = useSearchParams(); const allSearchParams = useMemo(() => { ...

Initiate a Gravity Forms form refresh after modifying a hidden field with jQuery

TO SUM IT UP: Is there a way in Javascript to activate an update on a Gravity Form that triggers the execution of conditional logic? ORIGINAL QUESTION: I'm using Gravity Forms and I have set up an "on change" event $('#gform_1').find(&apos ...

The concept of nested views in Angular UI-Router allows for a

How can I successfully implement nested views, where after logging in the user is redirected to in.html, and all links within in.html are directed to a ui-view? Currently, all links redirect to a new page. index.html <!-- more HTML --> <body ng- ...

Run JavaScript when ColdFusion page is being loaded

Within my ColdFusion page, I have incorporated multiple cfinclude template calls to bring in separate files. Before each cfinclude template call, I am seeking a way to update a javascript variable. I have attempted to achieve this by using: <script typ ...

Arranging a list of objects with a designated starting value to remain at the forefront

Consider the array and variable shown below: array = ['complete','in_progress','planned']; value = 'planned'; The goal is to always sort the array starting with the 'value' variable, resulting in: array ...

Utilizing Mongoose Schema Enums Alongside TypeScript Enums

In our Typescript-based NodeJs project utilizing Mongoose, we are seeking the right approach to define an enum field on a Mongoose schema that aligns with a Typescript enum. To illustrate, consider the following enum: enum StatusType { Approved = 1, ...

Link a function to a button in a 3rd party library

Whenever I click a button, there is a possibility of an alertify alert window appearing randomly. The alertify alert popup serves as a more aesthetically pleasing alternative to the traditional javascript Alert. Alertify library Below is a snapshot depic ...

Navigating with Anchors, Styling and jQuery

Firstly: Apologies in advance for any language errors as English is not my native tongue. :) The Scenario Here's the deal: I'm attempting to create a single button that, when clicked by the user, automatically scrolls down to the next DIV. Each ...

How can I combine multiple requests in RxJS, executing one request at a time in parallel, and receiving a single combined result?

For instance, assume I have 2 API services that return data in the form of Observables. function add(row) { let r = Math.ceil(Math.random() * 2000); let k = row + 1; return timer(r).pipe(mapTo(k)); } function multiple(row) { let r = Math.c ...

Transitioning from a multipage application to Piral: A comprehensive guide

Our organization operates several ASP.NET Core applications that are traditional multipage applications. As we develop a new portal using Piral, we want to incorporate elements from our existing applications while also introducing new modules. How can we ...

Preventing clicks underneath in Internet Explorer with CSS overlay

I am currently working on creating an overlay that is specifically designed to display in versions of Internet Explorer lower than 9, prompting users to upgrade their browsers. The overlay and message are functioning correctly, but I am facing an issue wit ...

Promise and Determination failing to produce results

const { GraphQLServer } = require('graphql-yoga'); const mongoose = require('mongoose'); mongoose.connect("mongodb://localhost/test1"); const Todo = mongoose.model('Todo',{ text: String, complete: Boolean }); const ...

Guide on retrieving file information after transmitting it to another PHP file through Ajax

I have written code to upload a file and send it to a php page. I would like the response to be an array containing information about the uploaded file such as name, size, type, etc. I am using the "POST" method for uploading the file. Is this approach cor ...