Reputation:
I am using custom next and previous to allow the user to navigate between multiple fancybox galleries, which works well. However -- when navigating between galleries, for some reason fancybox automatically selects the last image in the gallery.
I need to add a way to force fancybox to always load the first gallery image when it's initiated. By default, the index IS set to 0, which is a little confusing as to why it'd be changing.
Ideas? Here's my code.
Here is the code I'm working with:
var $thisFancyRel = 0;
var $itemsPerPage = 9;
$(".fancybox").fancybox({
index : 0,
helpers : {
title : {
type: 'outside'
},
thumbs : {
width : 50,
height : 50
}
},
afterLoad : function() {
var $self = $(this.element);
$thisFancyRel = parseInt($($self).attr("rel"));
},
afterShow : function() {
$button_next = "<div class='gallery__next'>Next</div>";
$button_prev = "<div class='gallery__prev'>Previous</div>";
$button_clear = "<div class='clearboth'></div>";
if($thisFancyRel > 0) {
if($thisFancyRel == 1) {
$buttons = $button_next + $button_clear;
} else if ($thisFancyRel == $itemsPerPage) {
$buttons = $button_prev + $button_clear;
} else {
$buttons = $button_prev + $button_next + $button_clear;
}
}
$(".fancybox-skin").after($buttons);
},
beforeClose : function() {
$thisFancyRel = 0;
}
});
$(document).on("click", ".gallery__next", function () {
var $nextFancyRel = $thisFancyRel + 1;
if($nextFancyRel > 0) {
var $relName = '.fancybox[rel="' + $nextFancyRel + '"]';
$.fancybox.close();
$($relName).trigger('click');
}
});
$(document).on("click", ".gallery__prev", function () {
var $prevFancyRel = $thisFancyRel - 1;
if($prevFancyRel > 0) {
var $relName = '.fancybox[rel="' + $prevFancyRel + '"]';
$.fancybox.close();
$($relName).trigger('click');
}
});
Upvotes: 0
Views: 1762
Reputation: 41143
The index
option works if you start your gallery directly from the anchor bound to fancybox.
On the other hand, if you start your gallery manually or using another element as a trigger, then the gallery will start from the last element found.
You can use the .eq()
method to start the gallery from the first item (or any other element) so try this in your code
$($relName).eq(0).trigger('click')
You may also see this https://stackoverflow.com/a/9435929/1055987 for reference.
BTW, if triggering a new gallery, you don't need to close fancybox so you can delete $.fancybox.close();
(opening a new instance will close the opened fancybox if any)
Upvotes: 1