jekyll-theme-isabelline/assets/js/gallery.js

94 lines
2.3 KiB
JavaScript
Raw Normal View History

2020-09-07 02:09:23 +00:00
(function () {
2020-09-07 16:49:16 +00:00
// "hydrate" div.gallery with play/pause and nav behaviors
2020-09-07 02:09:23 +00:00
var process_gallery = function (g) {
2020-09-07 16:49:16 +00:00
var
// milliseconds to wait before switch to next slide
NEXT_SLIDE_TIMEOUT = 5000;
var
// images in this gallery
images = g.querySelectorAll('.images img'),
// container for nav buttons
gallery_nav = g.querySelector('nav'),
// clickable buttons, one per image
// computed below
navs = [],
2020-09-07 02:09:23 +00:00
2020-09-07 16:49:16 +00:00
// index of the currently selected image
selected_index = 0,
// play control consists of a label and a checkbox
// defer computing because nav innerHTML gets clobbered
play_checkbox,
// handle to setInterval
play_interval;
// show image at index
// update nav controls accordingly
2020-09-07 02:09:23 +00:00
var select_image = function (index) {
// var image = images[index];
if (selected_index !== index) {
images[selected_index].style.display = 'none';
navs[selected_index].classList.remove('selected');
images[index].style.display = 'block';
navs[index].classList.add('selected');
selected_index = index;
}
}
2020-09-07 16:49:16 +00:00
// show next image
2020-09-07 02:09:23 +00:00
var next_image = function () {
if (selected_index >= images.length-1) {
select_image(0);
} else {
select_image(selected_index+1);
}
}
2020-09-07 16:49:16 +00:00
// handler for nav buttons
// selects an image corresponding to the clicked nav button
2020-09-07 02:09:23 +00:00
var nav_to_image = function () {
select_image(Array.from(navs).indexOf(this));
}
2020-09-07 16:49:16 +00:00
// play/pause slideshow
var toggle_play = function () {
if (play_checkbox.checked===true) {
clearInterval(play_interval);
} else {
play_interval = setInterval(next_image, NEXT_SLIDE_TIMEOUT);
}
}
2020-09-07 02:09:23 +00:00
var navHtml = '';
for (var i=0; i<images.length; ++i) {
var image = images[i]
image.addEventListener('click', next_image)
navHtml += '<i class="' + (i===0? 'selected' : '') + '" data-target="' + image.id + '"></i>'
}
2020-09-07 14:00:23 +00:00
gallery_nav.innerHTML += navHtml;
2020-09-07 02:09:23 +00:00
navs = gallery_nav.querySelectorAll('i');
2020-09-07 14:00:23 +00:00
2020-09-07 02:09:23 +00:00
for (var i=0; i<navs.length; ++i) {
var nav = navs[i];
nav.addEventListener('click', nav_to_image)
}
2020-09-07 16:49:16 +00:00
play_checkbox = g.querySelector('.play input[type=checkbox]');
play_checkbox.addEventListener('change', toggle_play);
2020-09-07 02:09:23 +00:00
}
2020-09-07 16:49:16 +00:00
var galleries = document.getElementsByClassName('gallery');
2020-09-07 02:09:23 +00:00
for (var i=0; i<galleries.length; ++i) {
var g = galleries[i];
process_gallery(g);
}
})();