jackmoore / colorbox

A light-weight, customizable lightbox plugin for jQuery
http://www.jacklmoore.com/colorbox/
MIT License
4.75k stars 1.14k forks source link

Custom order of slideshow items #646

Open ghost opened 10 years ago

ghost commented 10 years ago

Hi,

How can i change the order of items in colorbox slideshow(rel) to something else other than the order of DOM elements.

I have an attribute on each element with a date on it. I know how to sort it in ascending order. How can i make items show in that order in gallery?

<li class="js-colorbox" data-date="1884" rel="img"></li>  
<li class="js-colorbox" data-date="1886" rel="img"></li>  
<li class="js-colorbox" data-date="1885" rel="img"></li>

By clicking on first item i need the second one in slideshow to be item №3(with date 1885) even though it's after "1886" in DOM.

Mithgol commented 10 years ago

Instead of a simple $('.js-colorbox').colorbox(), try the following:

$('.js-colorbox').sort(function(prev, next){
   return $(prev).data('date') - $(next).data('date');
}).colorbox();

Note: jQuery's .sort method is not documented officially, but $('a').sort === [].sort is true and thus MDN docs for Array.prototype.sort can be used. However, use at your own risk.

ghost commented 10 years ago

Wow, thanks, @Mithgol. Exactly what i was looking for!

ghost commented 10 years ago

Ah. Unfortunately it doesn't work. Sorting works, but when you press "prev" or "next" colorbox doesn't respect it and follows it's usual order.

Update: made it work by changing the plugin itself. Maybe someone can point me how to make it work without changing the plugin to be able to use original order if i need to.

I changed function "getRelated":

  function getRelated(rel) {
    index = 0;

    if (rel && rel !== false && rel !== 'nofollow') {
      $related = $('.' + boxElement).filter(function () {
        var options = $.data(this, colorbox);
        var settings = new Settings(this, options);
        return (settings.get('rel') === rel);
      }).sort(function(prev, next) {
          if ($(prev).attr('data-date') > $(next).attr('data-date')) {
            return 1;
          } else {
            return -1;
          }
        });
      index = $related.index(settings.el);

      // Check direct calls to Colorbox.
      if (index === -1) {
        $related = $related.add(settings.el);
        index = $related.length - 1;
      }
    } else {
      $related = $(settings.el);
    }
  }