I'm trying to build simple javascript/jquery gallery. I suppose this is a pretty specific question.
The logic is as follows: to make as many divs as array contains elements(var sum). These elements present image names. I realized that in first for loop(first append function adds image and the second one adds name list - to navigate between images). In second for loop I set initial value (show me first image) and it works.
I met with an obstacle when trying to assign function to clicked element from name list. Third for loop obviously works(since it's copy of the second one). Is there any syntax error?
Code:
<div id="container"> //contains images
</div>
<div id="list"> //contains navigation numbers
</div>
<script>
var array = ['0', '1', '2']; //img names
var sum = array.length;
var currentId = 'a' + array[1];
$(document).ready(function () {
for (var i = 0; i < sum; i++) {
$("#container").append("<img class='a' src='img/" + array[i] + ".jpg' id='a" + array[i] + "'>");
$("#list").append("<a href='#a" + array[i] + "' onclick='checkButton()'>" + array[i] + "</a><br />");
}
for (var i = 0; i < sum; i++) {
var inactiveId = 'a' + array[i];
if (currentId !== inactiveId) {
document.getElementById(inactiveId).style.display = "none";
}
}
currentId1 = this.id;
$(currentId1).click(function () {
document.getElementById(currentId1).style.display = "block";
for (var i = 0; i < sum; i++) {
var inactiveId = 'a' + [i];
if (inactiveId !== currentId1) {
document.getElementById(inactiveId).style.display = "none";
}
}
})
});
</script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<div id="container">
<img id="dimg" src=""/>
</div>
<hr>
<div id="list">
</div>
<script>
var images = [
'http://www.qygjxz.com/data/out/208/5695232-smile-pics.png',
'https://i.pinimg.com/736x/a5/0b/9f/a50b9f1bb631d41623510a779741ca67.jpg',
'https://i.pinimg.com/736x/c0/1e/7e/c01e7e0b36c7edba6a90887dc63ac49d--smiley-happy-smile-face.jpg'
];
var sizes = {
width: 100,
height: 100
}
$(document).ready(function () {
// Define the default size for all images
$("#dimg").width(sizes.width).height(sizes.height);
// Show the image names
for (var i = 0; i < images.length; i++) {
let imgName = images[i].split("/");
let anchor = $("<a href='#' lnk='" + images[i] + "'>" + imgName[imgName.length-1] + "</a><br/>");
$("#list").append(anchor);
// Click event
anchor.on("click", function() {
$("#dimg").attr("src", $(this).attr("lnk"));
});
}
// Click to the first image name
$("#list a:eq(1)").trigger("click");
});
</script>