skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. Consider the following example.

    Fiddle: https://jsfiddle.net/Twisty/0ku35r7b/

    HTML

    <div id="content">
      <div id="picture">
        <img id="pic" src="https://dummyimage.com/480x340/ccc/000.jpg&text=Image0">
      </div>
    </div>
    
    <div id="buttons">
      <button id="previous" type="button" class="BUTTON_AUJ">Previous</button>
      <button id="update" type="button" class="BUTTON_AUJ">Slide Start</button>
      <button id="next" type="button" class="BUTTON_AUJ">Next</button>
    </div>
    

    JavaScript

     $(function() {
    
      var testData = {
        files: [
          "https://dummyimage.com/480x340/ccc/000.jpg&text=Image0",
          "https://dummyimage.com/480x340/ccc/000.jpg&text=Image1",
          "https://dummyimage.com/480x340/ccc/000.jpg&text=Image2",
          "https://dummyimage.com/480x340/ccc/000.jpg&text=Image3"
        ]
      };
    
      function getImages() {
        var myImages = [];
        $.post("/echo/json", {
          json: JSON.stringify(testData)
        }, function(results) {
          $.each(results.files, function(i, image) {
            myImages.push(image);
          });
        });
        $("#picture").data("index", 0);
        return myImages
      }
    
      function changePicture(index) {
        console.log("Change to Picture " + index);
        var current = $("#picture img");
        current.hide().attr("src", $("#picture").data("images")[index]).fadeIn();
      }
    
    
      function nextPicture() {
        console.log("Next");
        var index = $("#picture").data("index");
        console.log("Current Index: " + index);
        if (++index >= $("#picture").data("images").length) {
          index = 0;
        }
        console.log("Next Index: " + index);
        changePicture(index);
        $("#picture").data("index", index);
      }
    
      function previousPicture() {
        console.log("Previous");
        var index = $("#picture").data("index");
        console.log("Current Index: " + index);
        if (--index < 0) {
          index = $("#picture").data("images").length - 1;
        }
        console.log("Previous Index: " + index);
        changePicture(index);
        $("#picture").data("index", index);
      }
    
      function startRotation() {
        var interval = 3000;
        console.log("Start Rotation", interval);
        $("#picture").data("interval", setInterval(nextPicture, interval));
      }
    
      function stopRotation() {
        console.log("Stop Rotation");
        clearInterval($("#picture").data("interval"));
      }
    
      function main() {
        console.log("INIT");
        $("#picture").data("images", getImages());
        console.log($("#picture").data("images"));
        console.log($("#picture").data("index"));
      }
      main();
    
      $("#next").click(nextPicture);
      $("#previous").click(previousPicture);
      $("#update").click(function() {
        if (!$(this).data("rotate")) {
          startRotation();
          $(this).html("Slide Stop").data("rotate", true);
        } else {
          stopRotation();
          $(this).html("Slide Start").data("rotate", false);
        }
    
      });
    });
    

    This example makes use of JSFiddles Async options. Your AJAX Code will be different. I suggest something like:

    $.getJSON("file.json", function(results){ })`
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search