I'm a beginning coder, learned CSS, HTML, and Jquery in an internship this summer. My boss wants me to create a gallery that has one main image, and then two buttons to display the next or previous item. He wants me to use json, so that they can easily add and remove images. I have it written so that, I start with a variable 0, then when I click prev/next it decrements/increments the variable, and then goes back to the json to look for the corresponding picture. The only problem is that if I have four pictures, if the value goes below zero or above 3, it breaks.
How can I have the jquery tell if the json lookup returned undefined, so that I can have it either loop or disable the button? I suppose an if statement would be ideal, but I leave it to you.
$(document).ready(function(){
$.getJSON("layout.json",function(data){
// Then put the first picture up from the json data...
$("<img />").attr({
id: "0-middle_image",
class: "middle_image",
src: data.items[0].image ,
})
.appendTo("div#middle_image");
// because I'm starting with the zeroth object, middleimage variable is 0
var mi_val = 0
// when you click one of the cycle buttons...
$("div.cycle_button").click(function(){
//if it is the previous, decrement mi_val, else, increment mi_val
if ( $(this).attr("id") == "button_prev")
{--mi_val;}
else {++mi_val;}
//then, call the appropriate image object from the json
$("img.middle_image").fadeOut(500,function(){
$(this).attr({src: data.items[mi_val].image})
.fadeIn(500);
});
});
});
});