Search code examples
javascriptphoto-gallery

Photogallery previous button not functioning right


I'm playing around with learning javascript and am trying to make a very simple photo gallery. The next button I have works like it's suppose to advancing the photo one at a time, but when you hit previous it goes all the way back to the first image instead of just back one image and I can't quite figure out why. Thanks so much for any help.

It's in a jsbin here: http://jsbin.com/unijet/2/edit

My code is:

Html:

  <div id="navContainer">
  <span id="prev"><a href="" onClick="return prev_img();">Prev</a></span>
  <span id="pg"></span>
  <span id="next"><a href="" onClick="return next_img();">Next</a></span>
  </div>

  <div id="imgContainer"><img src="" id="img"/></div>

JS:

var prev = document.getElementById("prev");
var next = document.getElementById("next");
var imge = document.getElementById("img");
var page = document.getElementById("pg");    

var imag = [
    "http://images.nationalgeographic.com/wpf/media-live/photos/000/667/cache/red-fox-manitoba_66703_990x742.jpg",
    "http://images.nationalgeographic.com/wpf/media-live/photos/000/667/cache/martial-arts-india_66701_990x742.jpg?01AD=3Ha8VZ6-_SyLzHh6QoaApO6cxS3yLIp8X8QYWOgGUaWbdSUQ9pY9LJw&01RI=20FA22155E4E381&01NA=na",
    "http://images.nationalgeographic.com/wpf/media-live/photos/000/666/cache/egret-reflection-florida_66697_990x742.jpg",
    "http://images.nationalgeographic.com/wpf/media-live/photos/000/667/cache/tornado-storm-saskatchewan_66707_990x742.jpg",
    "http://images.nationalgeographic.com/wpf/media-live/photos/000/667/cache/penguin-south-georgia-island_66702_990x742.jpg",
    "http://images.nationalgeographic.com/wpf/media-live/photos/000/667/cache/sunset-south-africa_66706_990x742.jpg",
    "http://images.nationalgeographic.com/wpf/media-live/photos/000/667/cache/man-motorbike-india_66710_990x742.jpg"
];

var i = 0;

imge.setAttribute("src",imag[i]);
prev.innerHTML = "Prev";
page.innerHTML = i;

function next_img() {
    i++;
    page.innerHTML = i;
    imge.setAttribute("src",imag[i]);

    if (i == imag.length-1) {
        next.innerHTML = "Next";
        prev.innerHTML = "<a href='' onClick='return prev_img();'>Prev</a>";
    } else {
        next.innerHTML = "<a href='' onClick='return next_img();'>Next</a>";
        prev.innerHTML = "<a href='' onClick='return prev_img();'>Prev</a>";
    }
    return false;
}

function prev_img() {
    i--;
    page.innerHTML = i;
    image.setAttribute("src",imag[i]);

    if (i === 0) {
        prev.innerHTML = "Prev";
        next.innerHTML = "<a href='' onClick='return next_img();'>Next</a>";
    } else {
        prev.innerHTML = "<a href='' onClick='return prev_img();'>Prev</a>";
        next.innerHTML = "<a href='' onClick='return next_img();'>Next</a>";
    }
    return false;
}        

Solution

  • In the prev_img() function change

    image.setAttribute("src",imag[i]);
    

    to

    imge.setAttribute("src",imag[i]);