PhotoSwipe: edit parseThumbnailElements function to parse additional markup element - javascript

Using PhotoSwipe the thumbnail gallery markup looks like this:
<div class="wrap clearfix">
<div class="my-gallery" itemscope itemtype="http://schema.org/ImageGallery">
<ul class="gallery-grid">
<li>
<figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
<a href="img/dektop/1.jpg" itemprop="contentUrl" data-size="1200x1200">
<img src="img/thumb/1.jpg" itemprop="thumbnail" alt="Image description" />
</a>
<figcaption itemprop="caption description">Image caption 1</figcaption>
</figure>
</li>
<li>
<figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
<a href="img/dektop/2.jpg" itemprop="contentUrl" data-size="1200x1200">
<img src="img/thumb/2.jpg" itemprop="thumbnail" alt="Image description" />
</a>
<figcaption itemprop="caption description">Image caption 2</figcaption>
</figure>
</li>
</ul>
</div> <!-- mygallery -->
</div> <!-- wrap -->
The function to parse the images is:
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
// include only element nodes
if(figureEl.nodeType !== 1) {
continue;
}
linkEl = figureEl.children[0]; // <a> element
size = linkEl.getAttribute('data-size').split('x');
// create slide object
item = {
src: linkEl.getAttribute('href'),
w: parseInt(size[0], 10),
h: parseInt(size[1], 10)
};
if(figureEl.children.length > 1) {
// <figcaption> content
item.title = figureEl.children[1].innerHTML;
}
if(linkEl.children.length > 0) {
// <img> thumbnail element, retrieving thumbnail url
item.msrc = linkEl.children[0].getAttribute('src');
}
item.el = figureEl; // save link to element for getThumbBoundsFn
items.push(item);
}
return items;
};
I have two additional elements between the my-gallery and the figure class. Removing those things work perfect, however with the additional two classes I cannot select the previous or next item, meaning the array is broken.
How can I include the gallery-grid and li elements in the function so that is looks past those elements for figure and children.
Totally new to pure JS, any hints or further reading very welcome. Unfortunately with this one I have no clue where to even start looking.
http://quirksmode.org/dom/core/#gettingelements
https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName

I managed by leaving the original markup in place and change the CSS for the thumbnail gallery. It now works and looks like this:
<div class="wrap clearfix">
<div class="my-gallery gallery-grid" itemscope itemtype="http://schema.org/ImageGallery">
<figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
<a href="img/dektop/1.jpg" itemprop="contentUrl" data-size="1200x1200">
<img src="img/thumb/1.jpg" itemprop="thumbnail" alt="Image description" />
</a>
<figcaption itemprop="caption description">Image caption 4</figcaption>
</figure>
<figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
<a href="img/dektop/2.jpg" itemprop="contentUrl" data-size="1200x1200">
<img src="img/thumb/2.jpg" itemprop="thumbnail" alt="Image description" />
</a>
<figcaption itemprop="caption description">Image caption 4</figcaption>
</figure>
</div> <!-- mygallery -->
</div> <!-- wrap -->
And the CSS for the the thumbnail grid:
/* thumnail gallery grid */
.gallery-grid {
margin: 35px 0 0 0;
padding: 0;
list-style: none;
position: relative;
width: 100%;
}
.gallery-grid figure {
position: relative;
float: left;
overflow: hidden;
width: 16.6666667%; /* Fallback */
width: -webkit-calc(100% / 6);
width: calc(100% / 6);
height: 300px; /* pay attention to this later */
}
.gallery-grid figure a,
.gallery-grid figure a img {
display: block;
width: 100%;
height: auto;
cursor: pointer;
}
.gallery-grid figure a img {
width: 100%;
height: auto;
}
#media screen and (max-width: 1190px) {
.gallery-grid figure {
width: 20%; /* Fallback */
width: -webkit-calc(100% / 5);
width: calc(100% / 5);
}
}
#media screen and (max-width: 945px) {
.gallery-grid figure {
width: 25%; /* Fallback */
width: -webkit-calc(100% / 4);
width: calc(100% / 4);
}
}
#media screen and (max-width: 660px) {
.gallery-grid figure {
width: 33.3333333%; /* Fallback */
width: -webkit-calc(100% / 3);
width: calc(100% / 3);
}
}
#media screen and (max-width: 660px) {
.gallery-grid figure {
width: 33.3333333%; /* Fallback */
width: -webkit-calc(100% / 3);
width: calc(100% / 3);
}
}
#media screen and (max-width: 400px) {
.gallery-grid figure {
width: 50%; /* Fallback */
width: -webkit-calc(100% / 2);
width: calc(100% / 2);
}
}
#media screen and (max-width: 300px) {
.gallery-grid figure {
width: 100%;
}
}
However this is not really an answer but a workaround to accommodate for the original markup. I would still very much love to find out about how to change the JS to work with the markup from my question.
I am using the example from here:
http://photoswipe.com/documentation/getting-started.html
At the bottom there is a CodePen.

Old question and we had little bit different markup, but if somebody is trying to figure this out like me this might work as it did to me:
https://github.com/akizor/PhotoSwipe-Gallery-Improvement
All you need to do is include Photoswipe library, add a HTML tag that acts as a container for all your gallery images and use this javascript in your page.
I used div with a class .images-container as a container.
var initPhotoSwipeFromDOM = function(gallerySelector) {
var parseThumbnailElements = function(el) {
var all = document.querySelectorAll(gallerySelector);
var items = [];
for(var j = 0 ; j < all.length; j++){
var el = all[j];
var thumbElements = el.parentNode.childNodes;
var numNodes = thumbElements.length,
figureEl,
linkEl,
size,
item;
for(var i = 0; i < numNodes; i++) {
figureEl = thumbElements[i];
if(figureEl.nodeType !== 1) {
continue;
}
linkEl = figureEl.children[0];
size = linkEl.getAttribute('data-size').split('x');
item = {
src: linkEl.getAttribute('href'),
w: parseInt(size[0], 10),
h: parseInt(size[1], 10),
minZoom: 3
};
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 = document.querySelectorAll(gallerySelector),
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 = {
maxSpreadZoom: 5,
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};
},
minZoom: 3
};
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);
return 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 );
}
};
// execute above function
initPhotoSwipeFromDOM('.images-container figure');

Related

PhotoSwipe overlayed button click causes gallery to open

I'm trying to add a delete button overlayed on my thumbnails but when I click it the gallery is opened.
I tried adding this to try to stop the click propagating to the figure element but it didn't work:
$('body').on('click', '.delete-file-btn', function(e) {
e.preventDefault();
e.stopImmediatePropagation();
});
var initPhotoSwipeFromDOM = function(gallerySelector) {
// parse slide data (url, title, size ...) from DOM elements
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
// include only element nodes
if(figureEl.nodeType !== 1) {
continue;
}
linkEl = figureEl.children[0]; // <a> element
size = linkEl.getAttribute('data-size').split('x');
// create slide object
item = {
src: linkEl.getAttribute('href'),
w: parseInt(size[0], 10),
h: parseInt(size[1], 10)
};
if(figureEl.children.length > 1) {
// <figcaption> content
item.title = figureEl.children[1].innerHTML;
}
if(linkEl.children.length > 0) {
// <img> thumbnail element, retrieving thumbnail url
item.msrc = linkEl.children[0].getAttribute('src');
}
item.el = figureEl; // save link to element for getThumbBoundsFn
items.push(item);
}
return items;
};
// find nearest parent element
var closest = function closest(el, fn) {
return el && ( fn(el) ? el : closest(el.parentNode, fn) );
};
// triggers when user clicks on thumbnail
var onThumbnailsClick = function(e) {
e = e || window.event;
e.preventDefault ? e.preventDefault() : e.returnValue = false;
var eTarget = e.target || e.srcElement;
// find root element of slide
var clickedListItem = closest(eTarget, function(el) {
return (el.tagName && el.tagName.toUpperCase() === 'FIGURE');
});
if(!clickedListItem) {
return;
}
// find index of clicked item by looping through all child nodes
// alternatively, you may define index via data- attribute
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) {
// open PhotoSwipe if valid index found
openPhotoSwipe( index, clickedGallery );
}
return false;
};
// parse picture index and gallery index from URL (#&pid=1&gid=2)
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);
// define options (if needed)
options = {
// define gallery index (for URL)
galleryUID: galleryElement.getAttribute('data-pswp-uid'),
getThumbBoundsFn: function(index) {
// See Options -> getThumbBoundsFn section of documentation for more info
var thumbnail = items[index].el.getElementsByTagName('img')[0], // find thumbnail
pageYScroll = window.pageYOffset || document.documentElement.scrollTop,
rect = thumbnail.getBoundingClientRect();
return {x:rect.left, y:rect.top + pageYScroll, w:rect.width};
}
};
// PhotoSwipe opened from URL
if(fromURL) {
if(options.galleryPIDs) {
// parse real index when custom PIDs are used
// http://photoswipe.com/documentation/faq.html#custom-pid-in-url
for(var j = 0; j < items.length; j++) {
if(items[j].pid == index) {
options.index = j;
break;
}
}
} else {
// in URL indexes start from 1
options.index = parseInt(index, 10) - 1;
}
} else {
options.index = parseInt(index, 10);
}
// exit if index not found
if( isNaN(options.index) ) {
return;
}
if(disableAnimation) {
options.showAnimationDuration = 0;
}
// Pass data to PhotoSwipe and initialize it
gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
gallery.init();
};
// loop through all gallery elements and bind events
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;
}
// Parse URL and open gallery if it contains #&pid=3&gid=1
var hashData = photoswipeParseHash();
if(hashData.pid && hashData.gid) {
openPhotoSwipe( hashData.pid, galleryElements[ hashData.gid - 1 ], true, true );
}
};
initPhotoSwipeFromDOM('.existing-files');
.existing-files {
margin: 1rem -.5rem;
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.existing-files .file-container {
padding: .5rem;
text-align: center;
display: inline-block;
position: relative;
}
.delete-file-btn {
font-size: 0;
position: absolute;
display: block;
transform: scale(1);
width: 22px;
height: 22px;
border-radius: 40px;
background-color: #E2E8F0;
top: -1px;
right: -5px;
z-index: 100;
box-shadow: -2px 2px 6px 1px rgba(0, 0, 0, 0.25);
transition: background-color .15s ease-in-out,box-shadow .15s ease-in-out;
}
.delete-file-btn::after, .delete-file-btn::before {
content: "";
display: block;
position: absolute;
width: 12px;
height: 2px;
background-color: #000000;
transform: rotate(45deg);
border-radius: 5px;
top: 10px;
left: 5px;
transition: background-color .15s ease-in-out;
}
.delete-file-btn::after {
transform: rotate(-45deg);
}
.delete-file-btn:hover, .delete-file-btn:focus, .delete-file-btn:active {
box-shadow: none;
background-color: #A0AEC0;
}
.delete-file-btn:hover::after, .delete-file-btn:hover::before, .delete-file-btn:focus::after, .delete-file-btn:focus::before, .delete-file-btn:active::after, .delete-file-btn:active::before {
background-color: #FFFFFF;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.3/photoswipe.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.3/default-skin/default-skin.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.3/photoswipe.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.3/photoswipe-ui-default.js"></script>
<div class="existing-files">
<figure class="file-container">
<a data-size="304x171" data-turbolinks="false" class="gal" href="https://placeimg.com/304/171/nature"><img src="https://placeimg.com/304/171/nature"></a>
<a class="delete-file-btn" rel="nofollow" data-method="delete" href="#"></a>
</figure>
<figure class="file-container">
<a data-size="304x171" data-turbolinks="false" class="gal" href="https://placeimg.com/304/171/nature"><img src="https://placeimg.com/304/171/nature"></a>
<a class="delete-file-btn" rel="nofollow" data-method="delete" href="#"></a>
</figure>
</div>
<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
<!-- Background of PhotoSwipe.
It's a separate element as animating opacity is faster than rgba(). -->
<div class="pswp__bg"></div>
<!-- Slides wrapper with overflow:hidden. -->
<div class="pswp__scroll-wrap">
<!-- Container that holds slides.
PhotoSwipe keeps only 3 of them in the DOM to save memory.
Don't modify these 3 pswp__item elements, data is added later on. -->
<div class="pswp__container">
<div class="pswp__item"></div>
<div class="pswp__item"></div>
<div class="pswp__item"></div>
</div>
<!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
<div class="pswp__ui pswp__ui--hidden">
<div class="pswp__top-bar">
<!-- Controls are self-explanatory. Order can be changed. -->
<div class="pswp__counter"></div>
<button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
<button class="pswp__button pswp__button--share" title="Share"></button>
<button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
<button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
<!-- Preloader demo https://codepen.io/dimsemenov/pen/yyBWoR -->
<!-- element will get class pswp__preloader--active when preloader is running -->
<div class="pswp__preloader">
<div class="pswp__preloader__icn">
<div class="pswp__preloader__cut">
<div class="pswp__preloader__donut"></div>
</div>
</div>
</div>
</div>
<div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
<div class="pswp__share-tooltip"></div>
</div>
<button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
</button>
<button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
</button>
<div class="pswp__caption">
<div class="pswp__caption__center"></div>
</div>
</div>
</div>
</div>
Instead of preventing the click from propagating on elements it shouldn't I changed the script to only allow clicks on my gallery image anchor element class="gal" above. Here's the edited function from the script above.
var onThumbnailsClick = function(e) {
e = e || window.event;
e.preventDefault ? e.preventDefault() : e.returnValue = false;
var eTarget = e.target || e.srcElement;
// find root element of slide
var clickedListItem = closest(eTarget, function(el) {
return (el.tagName && el.tagName.toUpperCase() === 'A' && el.className == 'gal');
});
if(!clickedListItem) {
return;
}
// find index of clicked item by looping through all child nodes
// alternatively, you may define index via data- attribute
var clickedGallery = clickedListItem.parentNode.parentNode,
childNodes = clickedListItem.parentNode.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.parentNode) {
index = nodeIndex;
break;
}
nodeIndex++;
}
if(index >= 0) {
// open PhotoSwipe if valid index found
openPhotoSwipe( index, clickedGallery );
}
return false;
};

How can I fix this photo gallery?

I created or tried to make a Photo Gallery on one of my web pages. It worked perfectly at first, but when the "Show more images" button is clicked, it changes the logo and doesn't show the other added images. (See pictures below). How can I avoid the logo changing and show the rest of the photos?
I really will appreciate if somebody can help me to find the error. Thanks!
Here's the html code:
<h1 class="headings1">ABOUT US</h1>
<article>
<div id="leftarrow">
<p><</p>
</div>
<figure id="fig2">
<img class="about" width="360" height="202" />
</figure>
<figure id="fig3">
<img class="about" width="480" height="270" />
</figure>
<figure id="fig4">
<img class="about" width="360" height="202" />
</figure>
<div id="rightarrow">
<p>></p>
</div>
<div id="fiveButton">
<p>Show more images</p>
</div>
</article>
Here's javascript code:
"use strict"; // interpret document contents in JavaScript strict mode
/* global variables */
var photoOrder = [1,2,3,4,5];
var figureCount = 3;
/* add src values to img elements based on order specified on photoOrder array */
function populateFigures() {
var filename;
var currentFig;
if (figureCount === 3){
for (var i = 1; i < 4; i++) {
filename = "images/about_0" + photoOrder[i] + "sm.jpg";
currentFig = document.getElementsByClassName("about") [i - 1];
currentFig.src = filename;
}
} else {
for (var i = 0; i < 5; i++) {
filename = "image/about_0" + photoOrder[i] + "sm.jpg";
currentFig = document.getElementsByClassName("about")[1];
currentFig.src = filename;
}
}
}
/* shift all images one figure to the left, and change values in photoOrder array to match */
function rightArrow() {
for (var i = 0; i < 5; i++) {
if ((photoOrder[i] + 1) === 6) {
photoOrder[i] = 1;
} else {
photoOrder[i] += 1;
}
populateFigures();
}
}
/* shift all images one figure to the right, and change values in photoOrder array to match */
function leftArrow() {
for (var i = 0; i < 5; i++) {
if ((photoOrder[i] - 1) === 0) {
photoOrder[i] = 5;
} else {
photoOrder[i] -= 1;
}
populateFigures();
}
}
/* switch to 5-images */
function previewFive() {
//create figure and img elements for fifth image
var articleEl = document.getElementsByTagName("article")[0];
var lastFigure = document.createElement("figure");
lastFigure.id = "fig5";
lastFigure.style.zIndex = "5";
lastFigure.style.position = "absolute";
lastFigure.style.right = "45px"
lastFigure.style.top = "67px";
var lastImage = document.createElement("img");
lastImage.classList = "about";
lastImage.width = "240";
lastImage.height = "135"
lastFigure.appendChild(lastImage);
// articleEl.appendChild(lastFigure);
articleEl.insertBefore(lastFigure, document.getElementById("rightarrow"));
//clone figure element for fifth image and edit to be first image
var firstFigure = lastFigure.cloneNode(true);
firstFigure.id = "fig1";
firstFigure.style.right = "";
firstFigure.style.left = "45px";
// articleEl.appendChild(firstFigure);
articleEl.insertBefore(firstFigure, document.getElementById("fig2"));
//add appropiate src values to two img elements
document.getElementsByTagName("img")[0].src = "images/about_0" + photoOrder[0] + "sm.jpg";
document.getElementsByTagName("img")[4].src = "images/about_0" + photoOrder[4] + "sm.jpg";
figureCount = 5;
//change button to hide extra images
var numberButton = document.querySelector("#fiveButton p");
numberButton.innerHTML = "Show fewer images";
if (numberButton.addEventListener) {
numberButton.removeEventListener("click", previewFive, false);
numberButton.addEventListener("click", previewThree, false);
} else if (numberButton.attachEvent) {
numberButton.detachEvent("onclick", previewFive);
numberButton.attachEvent("onclick", previewThree);
}
}
/* switch to 3-image layout */
function previewThree() {
var articleEl = document.getElementsByTagName("article") [0];
var numberButton = document.querySelector("#fiveButton p");
articleEl.removeChild(document.getElementById("fig1"));
articleEl.removeChild(document.getElementById("fig5"));
figureCount = 3;
numberButton.innerHTML = "Show more images";
if (numberButton.addEventListener) {
numberButton.removeEventListener("click", previewThree, false);
numberButton.addEventListener("click", previewFive, false);
} else if (numberButton.attachEvent) {
numberButton.detachEvent("onclick", previewThree);
numberButton.attachEvent("onclick", previewFive);
}
}
/* Create event listener for left arrow, right arrow and center figure element */
function createEventListeners() {
var leftarrow = document.getElementById("leftarrow");
if (leftarrow.addEventListener) {
leftarrow.addEventListener("click", leftArrow, false);
} else if (leftarrow.attachEvent) {
leftarrow.attachEvent("onclick", leftArrow);
}
var rightarrow = document.getElementById("rightarrow");
if (rightarrow.addEventListener) {
rightarrow.addEventListener("click", rightArrow, false);
}else if (rightarrow.attachEvent) {
rightarrow.attachEvent("onclick", rightArrow);
}
var mainFig = document.getElementsByTagName("img")[1];
if (mainFig.addEventListener) {
mainFig.addEventListener("click", zoomFig, false);
} else if (mainFig.attachEvent) {
mainFig.attachEvent("onclick", zoomFig);
}
var showAllButton = document.querySelector("#fiveButton p");
if (showAllButton.addEventListener) {
showAllButton.addEventListener("click", previewFive, false);
}else if (showAllButton.attachEvent) {
showAllButton.attachEvent("onclick", previewFive);
}
}
/* open center figure in separate window */
function zoomFig() {
var propertyWidth = 960;
var propertyHeight = 600;
var winLeft = ((screen.width - propertyWidth) / 2);
var winTop = ((screen.height - propertyHeight) / 2);
var winOptions = "width = 960, height = 600";
winOptions += ",left=" + winLeft;
winOptions += ",top=" + winTop;
var zoomWindow = window.open("zoom.html", "zoomwin", winOptions);
zoomWindow.focus();
}
/* create event listeners and populate image elements */
function setUpPage() {
createEventListeners();
populateFigures();
}
/* run setUpPage() function when page finishes loading */
if (window.addEventListener) {
window.addEventListener("load", setUpPage, false);
} else if (window.attachEvent) {
window.attachEvent("onload", setUpPage);
}
I have included a tiny library with a constructor called ImgViewer. Admittedly, if you resize the screen vertically, it can be a slight issue, but it's all the time I'm willing to take right now. Hopefully you can learn something from this.
//<![CDATA[
/* js/external.js */
let doc, htm, bod, nav, M, I, mobile, S, Q, hC, aC, rC, tC, ImgViewer; // for use on other loads
addEventListener('load', ()=>{
doc = document; htm = doc.documentElement; bod = doc.body; nav = navigator; M = tag=>doc.createElement(tag); I = id=>doc.getElementById(id); mobile = /Mobi/i.test(nav.userAgent);
S = (selector, within)=>{
let w = within || doc;
return w.querySelector(selector);
}
Q = (selector, within)=>{
let w = within || doc;
return w.querySelectorAll(selector);
}
hC = (node, className)=>{
return node.classList.contains(className);
}
aC = (node, ...classNames)=>{
node.classList.add(...classNames);
return aC;
}
rC = (node, ...classNames)=>{
node.classList.remove(...classNames);
return rC;
}
tC = (node, className)=>{
node.classList.toggle(className);
return tC;
}
ImgViewer = function(imgArray, imgsWide = 3){
if(imgsWide % 2 === 0){
throw new Error('imgsWide must be odd number');
}
this.container = M('div'); this.leftArrow = M('div'); this.view = M('div');
this.rightArrow = M('div'); this.container.className = 'imgViewer';
this.view.className = 'view';
this.leftArrow.className = this.rightArrow.className = 'arrow';
this.leftArrow.textContent = '<'; this.rightArrow.textContent = '>';
this.container.appendChild(this.leftArrow); this.container.appendChild(this.view); this.container.appendChild(this.rightArrow);
const center = Math.floor(imgsWide/2), iA = [], imA = imgArray.slice();
this.size = ()=>{
const b = this.view.getBoundingClientRect(), w = b.width/imgsWide-40;
for(let i=0,l=iA.length; i<l; i++){
iA[i].width = i === center ? w+50 : w;
}
return this;
}
this.create = (where = bod)=>{ // default document.body
where.appendChild(this.container);
const v = this.view, b = v.getBoundingClientRect(), w = b.width/imgsWide-40;
for(let i=0,m,l=imgArray.length; i<l; i++){
m = M('img');
m.width = i === center ? w+50 : w;
m.src = imgArray[i]; iA.push(m); // cache all the images
if(i < imgsWide){
if(i === center){
// add a click event to center if you want - I did not
}
else if(i < center){
m.onclick = ()=>{
for(let n=i; n<center; n++){
this.rightArrow.onclick();
}
}
}
else{
m.onclick = ()=>{
for(let n=i; n<imgsWide; n++){
this.leftArrow.onclick();
}
}
}
v.appendChild(m);
}
}
const c = v.children;
const dispImgs = ()=>{
for(let n=0; n<imgsWide; n++){
c[n].src = imA[n];
}
}
this.leftArrow.onclick = ()=>{
imA.push(imA.shift()); dispImgs();
}
this.rightArrow.onclick = ()=>{
imA.unshift(imA.pop()); dispImgs();
}
onresize = this.size;
return this;
}
}
// tiny library above - magic below can be put on another page using a load Event except `}); // end load` line
const imgURLs = [
'https://images.freeimages.com/images/large-previews/afa/black-jaguar-1402097.jpg',
'https://images.freeimages.com/images/large-previews/7e9/ladybird-1367182.jpg',
'https://images.freeimages.com/images/large-previews/535/natural-wonders-1400924.jpg',
'https://images.freeimages.com/images/large-previews/035/young-golden-retriever-1404848.jpg',
'https://images.freeimages.com/images/large-previews/981/cow-1380252.jpg',
'https://images.freeimages.com/images/large-previews/9fc/yet-another-flower-1399208.jpg',
'https://images.freeimages.com/images/large-previews/72c/fox-1522156.jpg',
'https://images.freeimages.com/images/large-previews/e2a/boise-downtown-1387405.jpg',
'https://images.freeimages.com/images/large-previews/f37/cloudy-scotland-1392088.jpg'
];
const imgV = new ImgViewer(imgURLs);
imgV.create();
}); // end load
//]]>
/* css/external.css */
*{ /* size font individually to avoid font whitespace */
box-sizing:border-box; font-size:0; margin:0; padding:0; overflow:hidden;
}
html,body{
width:100%; height:100%;
} /* below is what you need to see - above is set for this example */
.imgViewer{
width:100%; height:100%;
}
.imgViewer,.imgViewer *{
display:flex; justify-content:center; align-items:center;
}
.imgViewer>.arrow{
cursor:pointer; width:32px; height:70px; background:#777; color:#fff; font:bold 14px san-serif;
}
.imgViewer>.view{
width:calc(100% - 32px); height:100%;
}
.imgViewer>.view>img{
cursor:pointer; margin:0 7px; box-shadow:1px 1px 2px;
}
.imgViewer>.view>img:first-child{
margin-left:0;
}
.imgViewer>.view>img:last-child{
margin-right:0;
}
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1, user-scalable=no' />
<title>ImgViewer</title>
<link type='text/css' rel='stylesheet' href='css/external.css' />
<script src='js/external.js'></script>
</head>
<body>
</body>
</html>
Of course, I didn't make the dummy window for zooming, but you can ask another question for that!

Computed Style doesn't show, graphically

I have a vertical navbar. When the client is on the website and viewing a section of the page that corresponds to the navbar button, that button should have a white border around it. When the client leaves that section for another section, that button should have a border around it and the last buttons border should disappear.
Unfortunately, only half of this works. I don't know why but when I scroll to another section the last sections corresponding button doesn't lose it's border, even though the debug messages state that the border color has been computed to be 'transparent'.
I've tried setting all faces of the border to transparent (top, bottom, left, right) and I've tried setting the style is jquery.
$(document).ready(() => {
$('.page').css('height', $(window).height());
$('.navbar').css('height', $(window).height());
})
let currentActiveButton = null;
document.addEventListener("scroll", () => {
let ids = calculateVisiblePages();
console.log(ids.join(", ") + "\n");
let heights = getVisibleHeights(ids);
let entry;
let highest = -1;
for (let i = 0; i < ids.length; i++) {
const id = ids[i];
if (highest == -1) {
highest = heights[id];
entry = id;
continue;
}
let height = heights[id];
if (highest < height) {
highest = height;
entry = id;
}
}
// console.log(`Highest: ${entry}`);
if (currentActiveButton === entry) return;
if (currentActiveButton != null) {
console.log(
`Attempting to set current active button, id is ${currentActiveButton}, to transparent.`
);
let activeButton = document.getElementById(currentActiveButton);
activeButton.style.borderColor = 'transparent';
let computedStyle = window.getComputedStyle(activeButton);
console.log(`Computes style border color: ${computedStyle.borderTopColor}`);
}
currentActiveButton = entry;
let buttons = document.getElementsByClassName("navbar_button");
switch (entry) {
case "projects": {
console.log("Case is projects.");
borderButton("portfolioButton");
return;
}
case "previousComms": {
borderButton("previousCommsButton");
return;
}
case "aboutMe": {
borderButton("aboutMeButton");
return;
}
}
});
// function getCurrentActiveButton() {
// let buttons = document.getElementsByClassName("navbar_button");
// for (let i = 0; i < buttons.length; i++) {
// const button = buttons[i];
// let computed = window.getComputedStyle(button);
// if (computed.borderTopColor.startsWith("rgba(255, 255, 255")) {
// return button;
// }
// }
// }
function borderButton(id) {
let button = document.getElementById(id);
let computedStyle = window.getComputedStyle(button);
button.style.borderColor = "white";
}
function calculateVisiblePages() {
let pages = document.getElementsByClassName("page");
let visible = [];
for (let i = 0; i < pages.length; i++) {
const page = pages[i];
if (isVisible(page)) visible.push(page.id);
}
return visible;
}
function isVisible(element) {
let elementTop = element.offsetTop;
let elementBottom =
elementTop + Number(element.style.height.replace("px", ""));
let viewportTop = window.scrollY;
let viewportBottom = viewportTop + window.innerHeight;
return elementBottom > viewportTop && elementTop < viewportBottom;
}
function getVisibleHeights(ids) {
let cache = {};
for (let i = 0; i < ids.length; i++) {
// console.log(`Iterating on element: ${ids[i]}`);
const element = document.getElementById(ids[i]);
let elementTop = element.offsetTop;
let elementBottom =
elementTop + Number(element.style.height.replace("px", ""));
let viewportBottom = window.scrollY + window.innerHeight;
let bottom = elementBottom - viewportBottom;
if (bottom < 0) bottom = elementBottom;
if (bottom < viewportBottom && viewportBottom < elementBottom)
bottom = viewportBottom;
let top = elementTop > window.scrollY ? elementTop : window.scrollY;
cache[element.id] = bottom - top;
// for (let i = elementTop; i < elementBottom; i++) {
// //Check if pixel is in element and in the viewport.
// // console.log(`Iteration: ${i}`);
// if (i < window.scrollY) continue;
// if (i > window.scrollY && i < elementBottom && i < viewportBottom) {
// cache[element.id] = i - window.scrollY;
// }
// }
}
return cache;
}
The CSS:
#import url(https://fonts.googleapis.com/css?family=Roboto:500&display=swap);
.root {
width: 100%;
height: 100%;
display: grid;
grid-template-columns: 95% 5%
}
.pages {
display: grid;
grid-template-rows: auto auto auto
}
.page {
height: 100%;
width: 100%
}
#projects {
background: #00f
}
#previousComms {
background: #ff0
}
#aboutMe {
background: red
}
.navbar_buttons_wrapper {
height: 100%;
width: 5%;
position: fixed;
top: 0;
right: 0
}
.navbar_buttons {
height: 100%;
display: flex;
align-items: center;
justify-content: center
}
.navbar_buttons ul {
height: auto;
list-style: none;
color: #fff;
padding: 0;
display: grid;
grid-template-columns: auto auto auto;
transform: rotate(-90deg)
}
.navbar_buttons ul li {
width: max-content;
margin-left: 30px;
margin-right: 30px;
font-size: 1.2rem;
text-transform: uppercase;
border-style: solid;
border-color: transparent;
transition: .7s;
padding: 7px
}
html body {
font-family: Roboto, sans-serif;
margin: 0;
border: 0;
padding: 0;
background: #2c2c2c
}
The HTML:
<html>
<head>
<link rel="stylesheet" type="text/css" href="./styles/main.css" />
<script type="text/javascript" src="./scripts/main-min.js"></script>
</head>
<body>
<div class="root">
<div class="pages">
<div class="page" id="projects"></div>
<div class="page" id="previousComms"></div>
<div class="page" id="aboutMe"></div>
</div>
<div class="navbar">
<div class="navbar_buttons_wrapper">
<div class="navbar_buttons">
<ul>
<li class="navbar_button" id="portfolioButton">Portfolio</li>
<li class="navbar_button" id="previousCommsButton">Previous Commissioners</li>
<li class="navbar_button" id="aboutMeButton">About Me</li>
</ul>
</div>
</div>
</div>
</div>
</body>
</html>
I had expected the border to change from white to transparent. However, all I got was no change to the color of the border of the button of the section I had previously been looking at on the website:
Before Movement: https://gyazo.com/77171adefe255973709f11e305bfb030
After Movement: https://gyazo.com/b121d1d33b4f5f205df1468cd936352b
Source Before Movement: https://gyazo.com/92359267cf06cbe3b7c4942f04dbf9ea
Source After Movement: https://gyazo.com/7cc03865e17fc42382774747fb30052a
Github Project File: https://github.com/TheMasteredPanda/Portfolio-Website/blob/master/src/scripts/src/navbarBorderManagement.js#L32
Your problem is inconsistent naming conventions between your ID's and it's causing your element objects to get obfuscated, so if for example you were to breakpoint where you're setting your borderColor to reset it back to transparent, you'd see you're hitting a page HTMLDivElement and not the li you're aiming for. See changes below and have a great weekend, cheers!
$(document).ready(() => {
$('.page').css('height', $(window).height());
$('.navbar').css('height', $(window).height());
})
let currentActiveButton = null;
document.addEventListener("scroll", () => {
let ids = calculateVisiblePages();
console.log(ids.join(", ") + "\n");
let heights = getVisibleHeights(ids);
let entry;
let highest = -1;
for (let i = 0; i < ids.length; i++) {
const id = ids[i];
if (highest == -1) {
highest = heights[id];
entry = id;
continue;
}
let height = heights[id];
if (highest < height) {
highest = height;
entry = id;
}
}
// console.log(`Highest: ${entry}`);
if (currentActiveButton === entry) return;
if (currentActiveButton != null) {
console.log(
`Attempting to set current active button, id is ${currentActiveButton}, to transparent.`
);
let activeButton = document.getElementById(currentActiveButton + 'Button');
activeButton.style.borderColor = 'transparent';
let computedStyle = window.getComputedStyle(activeButton);
console.log(`Computes style border color: ${computedStyle.borderTopColor}`);
}
currentActiveButton = entry;
let buttons = document.getElementsByClassName("navbar_button");
switch (entry) {
case "projects": {
console.log("Case is projects.");
borderButton("projectsButton");
return;
}
case "previousComms": {
borderButton("previousCommsButton");
return;
}
case "aboutMe": {
borderButton("aboutMeButton");
return;
}
}
});
// function getCurrentActiveButton() {
// let buttons = document.getElementsByClassName("navbar_button");
// for (let i = 0; i < buttons.length; i++) {
// const button = buttons[i];
// let computed = window.getComputedStyle(button);
// if (computed.borderTopColor.startsWith("rgba(255, 255, 255")) {
// return button;
// }
// }
// }
function borderButton(id) {
let button = document.getElementById(id);
let computedStyle = window.getComputedStyle(button);
button.style.borderColor = "white";
}
function calculateVisiblePages() {
let pages = document.getElementsByClassName("page");
let visible = [];
for (let i = 0; i < pages.length; i++) {
const page = pages[i];
if (isVisible(page)) visible.push(page.id);
}
return visible;
}
function isVisible(element) {
let elementTop = element.offsetTop;
let elementBottom =
elementTop + Number(element.style.height.replace("px", ""));
let viewportTop = window.scrollY;
let viewportBottom = viewportTop + window.innerHeight;
return elementBottom > viewportTop && elementTop < viewportBottom;
}
function getVisibleHeights(ids) {
let cache = {};
for (let i = 0; i < ids.length; i++) {
// console.log(`Iterating on element: ${ids[i]}`);
const element = document.getElementById(ids[i]);
let elementTop = element.offsetTop;
let elementBottom =
elementTop + Number(element.style.height.replace("px", ""));
let viewportBottom = window.scrollY + window.innerHeight;
let bottom = elementBottom - viewportBottom;
if (bottom < 0) bottom = elementBottom;
if (bottom < viewportBottom && viewportBottom < elementBottom)
bottom = viewportBottom;
let top = elementTop > window.scrollY ? elementTop : window.scrollY;
cache[element.id] = bottom - top;
// for (let i = elementTop; i < elementBottom; i++) {
// //Check if pixel is in element and in the viewport.
// // console.log(`Iteration: ${i}`);
// if (i < window.scrollY) continue;
// if (i > window.scrollY && i < elementBottom && i < viewportBottom) {
// cache[element.id] = i - window.scrollY;
// }
// }
}
return cache;
}
#import url(https://fonts.googleapis.com/css?family=Roboto:500&display=swap);
.root {
width: 100%;
height: 100%;
display: grid;
grid-template-columns: 95% 5%
}
.pages {
display: grid;
grid-template-rows: auto auto auto
}
.page {
height: 100%;
width: 100%
}
#projects {
background: #00f
}
#previousComms {
background: #ff0
}
#aboutMe {
background: red
}
.navbar_buttons_wrapper {
height: 100%;
width: 5%;
position: fixed;
top: 0;
right: 0
}
.navbar_buttons {
height: 100%;
display: flex;
align-items: center;
justify-content: center
}
.navbar_buttons ul {
height: auto;
list-style: none;
color: #fff;
padding: 0;
display: grid;
grid-template-columns: auto auto auto;
transform: rotate(-90deg)
}
.navbar_buttons ul li {
width: max-content;
margin-left: 30px;
margin-right: 30px;
font-size: 1.2rem;
text-transform: uppercase;
border-style: solid;
border-color: transparent;
transition: .7s;
padding: 7px
}
html body {
font-family: Roboto, sans-serif;
margin: 0;
border: 0;
padding: 0;
background: #2c2c2c
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head>
<link rel="stylesheet" type="text/css" href="./styles/main.css" />
<script type="text/javascript" src="./scripts/main-min.js"></script>
</head>
<body>
<div class="root">
<div class="pages">
<div class="page" id="projects"></div>
<div class="page" id="previousComms"></div>
<div class="page" id="aboutMe"></div>
</div>
<div class="navbar">
<div class="navbar_buttons_wrapper">
<div class="navbar_buttons">
<ul>
<li class="navbar_button" id="projectsButton">Portfolio</li>
<li class="navbar_button" id="previousCommsButton">Previous Commissioners</li>
<li class="navbar_button" id="aboutMeButton">About Me</li>
</ul>
</div>
</div>
</div>
</div>
</body>
</html>

I have made a Image Slider but want to add text to it each slide

I am learning javascript. I have made a image slider but want to add text to each slide I have 5 images just want to add the text to each slide and it be in the middle and centre from top to bottom. Thanks guys
var i = 0;
var images = [];
var time = 3250;
// Image List
images[0] = 'http://lorempixel.com/300/200';
images[1] = 'http://placehold.it/300x200';
images[2] = 'http://lorempixel.com/300/200';
images[3] = 'http://placehold.it/300x200';
images[4] = 'http://lorempixel.com/300/200';
// Change Image
function changeImg(){
document.slide.src = images[i];
if (i < images.length - 1) {
i++;
} else {
i = 0;
}
setTimeout("changeImg()", time);
}
window.onload = changeImg;
* {margin:0;padding:0;box-sizing:border-box}
#wrapper {
width: 800px;
height: 400px;
margin: 50px auto;
}
<h1>JS Slider </h1>
<div id="wrapper">
<img name="slide" alt="slide image">
</div>
In order to display unique text per picture, you first have to implement an object that holds these two values:
var images = [];
function appendImage(src, text) {
images.push({
src: src,
text: text
});
}
Then create your 5 images like so:
appendImage('1.jpg', 'Picture 1');
appendImage('2.jpg', 'Picture 2');
appendImage('3.jpg', 'Picture 3');
appendImage('4.jpg', 'Picture 4');
appendImage('5.jpg', 'Picture 5');
Just make sure you have an element that's propely placed (using CSS) to fill with text
<div id="wrapper">
<img name="slide" alt="slide image">
<span id="sliderText"></span>
</div>
The change to your changeImg function will be minor, you just need to consider the new data structure.
var sliderText = document.getElementById('sliderText');
function changeImg(){
document.slide.src = images[i].src;
sliderText.innerHTML = images[i].text;
if (i < images.length - 1) {
i++;
} else {
i = 0;
}
setTimeout("changeImg()", time);
}
You can use javascript objects:
var i = 0;
var images = [];
var time = 3250;
// Image List
images[0] = {
url: 'http://via.placeholder.com/120x120',
caption: '120x120'
};
images[1] = {
url: 'http://via.placeholder.com/130x130',
caption: '130x130'
};
images[2] = {
url: 'http://via.placeholder.com/140x140',
caption: '140x140'
};
images[3] = {
url: 'http://via.placeholder.com/150x150',
caption: '150x150'
};
images[4] = {
url: 'http://via.placeholder.com/160x160',
caption: '160x160'
};
// Change Image
function changeImg() {
document.slide.src = images[i].url;
caption.innerText = images[i].caption;
if (i < images.length - 1) {
i++;
} else {
i = 0;
}
setTimeout("changeImg()", time);
}
window.onload = changeImg;
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
#wrapper {
width: 800px;
height: 400px;
margin: 50px auto;
}
<h1>JS Slider </h1>
<div id="wrapper">
<img name="slide" alt="slide image">
<div id="caption">2134234</div>
</div>
jsfiddle

fancybox wrong image quantity with slick slider

I'm using fancybox to display image gallery.
I have this layout:
<div class="avatar">
<a class="avatar-item" data-fancybox="group" data-caption="Caption #1" href="img/avatars/jessica1.jpeg">
<img src="./img/avatars/jessica1.jpeg" width="145" height="145" alt="">
</a>
<a class="avatar-item" data-fancybox="group" data-caption="Caption #2" href="img/avatars/jessica2.jpeg">
<img src="./img/avatars/jessica2.jpeg" alt="">
</a>
</div>
And when I click on preview - gallery popup occurs, but it shows 4 images instead of 2. I included fancybox via data-attributes, without javascript. Tried magnific popup with gallery option - got same result.
link href attribute value and internal image src attribute are the same.
I don't have a thumbnail, display image cropped with css.
Hee is CSS:
.avatar {
&.slick-dotted.slick-slider {
margin-bottom: 0;
}
a.avatar-item {
width: 146px;
height: 146px;
display: inline-block;
}
width: 146px;
height: 146px;
border: 4px solid #FFF;
float: left;
position: relative;
overflow: hidden;
img {
height: 100%;
}
}
Found the problem. I use slick-slider before with infinite: true parameter, which creates an extra slides, so I got count slides x2
I have extended the _run function. Now duplicate images are removed from the gallery and still the correct key is returned. Furthermore I have the possibility to arrange the images in any order via data-facybox position.
So it is also possible to use the infinity version of the slick slider.
function _run(e, opts) {
var tempItems,
items = [],
newItem,
reOrder,
duplicates = false,
pos,
index = 0,
$target,
value,
instance;
// Avoid opening multiple times
if (e && e.isDefaultPrevented()) {
return;
}
e.preventDefault();
opts = opts || {};
if (e && e.data) {
opts = mergeOpts(e.data.options, opts);
}
$target = opts.$target || $(e.currentTarget).trigger("blur");
instance = $.fancybox.getInstance();
if (instance && instance.$trigger && instance.$trigger.is($target)) {
return;
}
if (opts.selector) {
tempItems = $(opts.selector);
} else {
// Get all related items and find index for clicked one
value = $target.attr("data-fancybox") || "";
if (value) {
tempItems = e.data ? e.data.items : [];
tempItems = tempItems.length ? tempItems.filter('[data-fancybox="' +
value + '"]') : $('[data-fancybox="' + value + '"]');
} else {
tempItems = [$target];
}
}
if (tempItems.length > 1) {
$.each(tempItems, function(key, item) { // prevents duplicate images in the gallery
newItem = false;
if (typeof item !== 'undefined') {
if (items.length > 0) {
var found = items.filter(function (items) { return items.href ==
item.href });
if (found.length == 0) {
newItem = true;
} else {
duplicates = true;
}
} else {
newItem = true;
}
}
if (newItem) {
// Sort if the attribute data-fancybox-pos exists
if ($(item).data('fancybox-pos')) {
reOrder = true;
pos = $(item).data('fancybox-pos') - 1;
if (pos in items) {
tempItem = items[pos];
items[pos] = item;
items.push(tempItem);
} else {
items[pos] = item;
}
} else {
items.push(item);
}
}
});
} else {
items = tempItems;
}
if (duplicates || reOrder) {
// find correct index if there were duplicates
$.each(items, function(key, item) {
if (item.href == $target[0].href) {
index = key;
}
});
} else {
index = $(items).index($target);
}
// Sometimes current item can not be found
if (index < 0) {
index = 0;
}
instance = $.fancybox.open(items, opts, index);
// Save last active element
instance.$trigger = $target;
}

Categories

Resources