简体   繁体   中英

How to add previous and next arrows for image gallery ?

I have a image gallery of about 30 photo with a thumbnails strip. Because of the big loading time of the images I added a on .click() event so that the image is loaded only when you click the thumbnail not all at once. The way i did it was by adding a small 1x1 dummy.jpg to be loaded instead of the real image that now is loaded only when clicking the thumbnail. The problem is I also have arrows for next and previous image that don't work anymore because they load the dummy.jpg not the real .jpg image.

This is the code i have:

For the arrows:

<div class="nav-icons">
<a href="#" class="prev_image" title="Previous Image"></a>
<a href="#" class="next_image" title="Next Image"></a>
</div>

For the thumbnail strip:

<div id="slider">
<img src="userfiles/images/photo1.jpg" class="image1" onclick="loadImage( 1 )" width="185" height="123" />
<img src="userfiles/images/photo2.jpg" class="image2" onclick="loadImage( 2 )" width="185" height="123" />
<img src="userfiles/images/photo3.jpg" class="image3" onclick="loadImage( 3 )" width="189" height="123" />
</div>

For the image:

<div id="fotoblock">
<img src="dummy.jpg" id="image1" width="1920" height="1075"  />
<img src="dummy.jpg" id="image2" width="1920" height="1075"  />
<img src="dummy.jpg" id="image3" width="1920" height="1075"  />
</div>

And the JS for the onClick event is:

<script language="javascript"> 
function loadImage( id ) {
 var image = document.getElementById( 'image'+id );
 image.setAttribute( 'src', 'userfiles/photo'+id+'.jpg' );
}
</script>

How can i get the arrows to load the real image when clicked?

With your code it is a little difficult to retrofit this into it, the quickest way to achieve what you need would be to store a global variable. And then run the function as below.But i suggest you look into oop with javascript, and jquery which would make this really easy as the sollution bellow is far from complete and a little messy as it puts variables into the document scope

<div class="nav-icons">
<a href="#" class="prev_image" title="Previous Image" onclick="moveImage('left')"></a>
<a href="#" class="next_image" title="Next Image" onclick="moveImage('right')"></a>
</div>

<script>
var current = 1;
function moveImage(direction){
   if(direction == "left"){
      loadImage( current - 1 );
   }else{
     loadImage( current + 1 );
   }  
}

function loadImage( id ) {
 var image = document.getElementById( 'image'+id );
 image.setAttribute( 'src', 'userfiles/photo'+id+'.jpg' );
 current = id;
}
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM