Created
June 12, 2017 02:57
-
-
Save johnscillieri/f83a5ca0ef5d4e6fb7c616e00d36d247 to your computer and use it in GitHub Desktop.
Javascript for a basic image gallery
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var jsonArray = {}; | |
var windowSize = 3; | |
var tailImage = 0; | |
function mod(n, m) { | |
return (n % m + m) % m; | |
} | |
$(document).ready(function() { | |
$.getJSON("data.json", function(data) { | |
jsonArray = data; | |
if (windowSize > jsonArray.length) { | |
windowSize = jsonArray.length; | |
} | |
tailImage = mod(0 - Math.floor(windowSize / 2), jsonArray.length); | |
var pictureFrame = document.getElementById("picture-frame"); | |
for (var i = 0; i < windowSize; i++) { | |
var elem = document.createElement("img"); | |
elem.style.visibility = "hidden"; | |
elem.src = jsonArray[mod(tailImage + i, jsonArray.length)].image; | |
// if it's the middle element, show it on load | |
if (i == Math.floor(windowSize / 2)) { | |
elem.onload = function() { | |
this.style.visibility = "visible"; | |
}; | |
} | |
pictureFrame.appendChild(elem); | |
} | |
setPictureInfo(); | |
console.log("After SPI: " + new Date().getTime()); | |
}); | |
}); | |
$(window).on("load", function() { | |
console.log("After load: " + new Date().getTime()); | |
}); | |
var setPictureInfo = function() { | |
var currentPicture = mod(tailImage + Math.floor(windowSize / 2), jsonArray.length); | |
var pictureInfo = jsonArray[currentPicture]; | |
var idLabel = document.getElementById("picture-id-label"); | |
idLabel.innerHTML = pictureInfo.id; | |
var dateLabel = document.getElementById("date-label"); | |
dateLabel.innerHTML = pictureInfo.date; | |
var children = document.getElementById("picture-frame").children; | |
for (var i = 0; i < windowSize; i++) { | |
var elem = children[i]; | |
elem.src = jsonArray[mod(tailImage + i, jsonArray.length)].image; | |
} | |
}; | |
var nextPicture = function() { | |
tailImage = mod(tailImage + 1, jsonArray.length); | |
setPictureInfo(); | |
}; | |
var previousPicture = function() { | |
tailImage = mod(tailImage - 1, jsonArray.length); | |
setPictureInfo(); | |
}; | |
$(document).keydown(function(e) { | |
switch (e.which) { | |
case 37: // left | |
previousPicture(); | |
break; | |
case 39: // right | |
nextPicture(); | |
break; | |
default: | |
return; // exit this handler for other keys | |
} | |
e.preventDefault(); // prevent the default action (scroll / move caret) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment