Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You need to initialize an object or array called <code>image</code> before you can add items to it.</p> <pre><code> var image = {}; image[3] = "http://farm5.static.flickr.com/4006/5131022085_62876bbfbd_b.jpg"; image[2] = "http://farm6.static.flickr.com/5201/5289991939_46a20dd9fd_o.jpg"; image[1] = "http://farm3.static.flickr.com/2127/5807551517_72d39a1d19_b.jpg"; </code></pre> <p>And if your function is the only one using <code>image</code>, I'd take it out of the function, and have it scoped in the IIFE:</p> <pre><code>(function($) { var image = {}; image[3] = "http://farm5.static.flickr.com/4006/5131022085_62876bbfbd_b.jpg"; image[2] = "http://farm6.static.flickr.com/5201/5289991939_46a20dd9fd_o.jpg"; image[1] = "http://farm3.static.flickr.com/2127/5807551517_72d39a1d19_b.jpg"; function browseImages(type) { // you could take `imageObject` out of this function as well if the // element with the ID "image" never changes. // v-------------------------------------------------------------- var imageObject = $("#image"); var selection; if (type == "left") { for (var i=1; i &lt; Things.length; i++) { if (imageObject.attr("src") == Things[i]) { selection = i; } // &lt;--- removed semi-colon } // &lt;--- removed semi-colon // v----- use the cached object imageObject.attr("src",image[selection]); } else { for (var i=1; i &lt; Things.length; i++) { if (imageObject.attr("src") == Things[i]) { selection = i; } // &lt;--- removed semi-colon } // &lt;--- removed semi-colon // v----- use the cached object imageObject.attr("src",image[selection]); } // &lt;--- removed semi-colon } init = function() { $("h1").click( function() { browseImages("left") }); }; })( jQuery ); </code></pre> <hr> <p><strong>EDIT:</strong> After some clarification, here's a simpler solution:</p> <pre><code>(function($) { var image = [ "http://farm3.static.flickr.com/2127/5807551517_72d39a1d19_b.jpg", "http://farm6.static.flickr.com/5201/5289991939_46a20dd9fd_o.jpg", "http://farm5.static.flickr.com/4006/5131022085_62876bbfbd_b.jpg" ]; var imageObject = $("#image"); var selection = 0; function browseImages(type) { if (type == "left") { selection = ++selection % image.length } else { selection = (selection || image.length); --selection; } imageObject.attr("src", image[selection]); } init = function() { $("h1").click(function() { browseImages("left") }); }; })(jQuery); jQuery(document).ready( init ); </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