Reputation: 299
I'm building a static page where I have an image and 2 arrows (one on the left of the image and one on the right). By clicking the arrow another image would appear, like in a photo gallery. There's only 4 images in total, which I would keep in the site folder on my computer. Basically the arrows should allow the user to cycle between the images, by pressing the right arrow or the left arrow.
I have an array of images:
var imageArray = new Array();
imageArray[0] = new Image(); imageArray[0].src = 'image1.png';
imageArray[1] = new Image(); imageArray[1].src = 'image2.png';
imageArray[2] = new Image(); imgArray[2].src = 'image3.png';
imageArray[3] = new Image(); imageArray[3].src = 'image4.png';
And the two arrows:
<div id="apDiv1"style="display:none"><img src="arrow left.png" width="125" height="74" onClick="SOMETHING">/div>
<div id="apDiv2"style="display:none"><img src="arrow right.png" width="125" height="74" onClick="SOMETHING">/div
I want to make onClick to call a function that shows the next (or previous) image.
How can I do this? I though of a sort of toggle function but that would work poorly.
And also, can I set up a starting image like:
<div id="apDiv3"style="display:none"><img src="image1.png" width="200" height="200">/div>
Upvotes: 0
Views: 687
Reputation: 4824
TO Move Forward (Forward Click)
css:
.show {
display: block;
}
.hide {
display: none;
}
Now, suppose you have a parent div with all image divs like this
<div class='parent'>
<div id='image-1' class='show'><img src="image1.png" width="200" height="200"></div>
<div id='image-2' class='hide'><img src="image2.png" width="200" height="200"></div>
<div id='image-3' class='hide'><img src="image3.png" width="200" height="200"></div>
//and so on...
</div>
Javascript code:
onclick: function() {
var images = $('.parent').find('div');
for(var i = 0; i< images.length; i++) {
if($(images[i]).hasClass('show')) {
$(images[i]).removeClass('show');
$(images[i]).addClass('hide');
if(i === images.length -1) {
$(images[0]).removeClass('hide');
$(images[0]).addClass('show');
} else {
$(images[0]).removeClass('show');
$(images[0]).addClass('hide');
}
}
}
}
Similarly, implement for back arrow click
Hope this helps
Upvotes: 1