I’m trying to create a photo gallery using Ajax and JQuery in Javascript.
I have a folder created in VSC called "images" and inside it I have my 5 chosen images.
Unfortunately, once I click the "next" and "previous" buttons, the images are not showing. In the console it says that the photos are undefined. Any ideas as to how I can solve this issue? I would greatly appreciate the help as I’m quite new to all this!
Below is my HTML and JS code:
<div id="content">
<div id="picture">
<img id="pic" src="images/image1.jpg">
</div>
</div>
<div id="buttons">
<button id="previous" type="button" class="BUTTON_AUJ">Previous</button>
<button id="update" type="button" class="BUTTON_AUJ">Update</button>
<button id="next" type="button" class="BUTTON_AUJ">Next</button>
</div>
'use strict';
$(document).ready(function () {
var max_index = null, min_index = 0;
var timeID = null;
var index = 0;
var files = [];
function changePicture(pics){
$("#pic").attr("src", "images/" + pics);
$("#picture").hide().fadeIn("slow");
}
function loadImages() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4) {
files = JSON.parse(this.responseText).files;
max_index = files.length - 1;
changePicture(files[index]);
rotating(files[min_index]);
}
};
xhttp.open("GET", "file.html", true);
xhttp.send();
}
function nextPicture(){
if (index < max_index)
index++;
else
index = min_index;
changePicture(files[index]);
rotating(files[index]);
}
function previousPicture() {
if (index > min_index)
index--;
else
index = max_index;
changePicture(files[index]);
rotating(files[index]);
}
function rotating(filename){
var interval = filename.split("_")[1].replace(".jpg", "") * 1000;
if (timeID) {
clearTimeout(timeID);
timeID = null;
}
timeID = setTimeout(nextPicture, interval);
}
function main(){
loadImages();
}
main();
$("#next").click(function () {
nextPicture();
});
$("#previous").click(function () {
previousPicture();
});
$("update").click(function(){
index = 0;
loadImages();
});
});
2
Answers
Try to simply your code add
Document.getElementById to the body or bodyonload then run a function and add an image using the tag as thats how you add images on javascript standard
Consider the following example.
Fiddle: https://jsfiddle.net/Twisty/0ku35r7b/
HTML
JavaScript
This example makes use of JSFiddles Async options. Your AJAX Code will be different. I suggest something like:
This flushes out the functions a bit more and uses the
.data()
feature to store images, index, intervals in the attributes of the elements. This makes them more available to different functions. There is nothing wrong with storing them in Global variables. If you have more than one, storing their indexes and Image lists with them makes them easy to access.Most scripts will have a few images in play and animate the change, giving it a slide show or carousel effect. Since you’re just showing one, it’s easy enough to just change the source.