Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>OK, I understand the problem now I think.</p> <p>I would generalise the image-swapping code into a function that swaps out the current image given an index. I've called this function <code>setImageWithIndex()</code>. Then we can deal simply with what the index is in the <code>.click()</code> code.</p> <p>This requires saving the <code>data</code> into another global, <code>jsonData</code>.</p> <p>I would also save (a) the number of images returned in the JSON data and (b) the current image index (initially zero) in two global variables.</p> <p>Here's the code. I've also removed some jquery and replaced it with standard javascript where it doesn't really add anything.</p> <pre><code>var imageCount; var currentImage = 0; var jsonData; function setImageWithIndex(index) { $("img.middle_image").fadeOut(500, function() { $("img.middle_image") .attr({src: jsonData.items[index].image}) .fadeIn(500); }); } window.onload = function() { $.getJSON("layout.json", function(data) { jsonData = data; $("&lt;img /&gt;").attr({ id: "0-middle_image", class: "middle_image", src: data.items[0].image }) .appendTo("div#middle_image"); /* &lt;PSEUDOCODE class="may not work"&gt; */ imageCount = data.items[0].length; // ie: save the number of images in a global variable /* &lt;/PSEUDOCODE&gt; */ } $("div.cycle_button").click(function() { if (this.id == "button_prev") if (currentImage &gt; 0) setImageWithIndex(--currentImage); else if (currentImage &lt; imageCount) setImageWithIndex(++currentImage); }); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload