Search code examples
jqueryimagesliderjquery-selectorsgallery

jquery next previous with non-preload image


I'm creating a very simple image gallery that only load the first image of the gallery. User need to click on the thumbnail to view the image. This is because I'm using a large image for the gallery so that it don't have to load every image. And right now I'm having a problem creating a next and previous button.

This is the where the image load

<div class="entry-content">
<div class="img-box">
<img id="img-preview" src="#" >
</div>
</div>                          

This is the pagination

<div class="paginate">  
<a href="#" class="prev"></a>
<a href="#" class="next"></a>
</div>

This is where the thumbnail belong

<ul id="related-category"> 
<li class="photo"><a href="#" ></a></li>
<li class="photo"><a href="#" ></a></li>
<li class="photo"><a href="#" ></a></li>
<li class="photo"><a href="#" ></a></li>
</ul> 

JQUERY

jqu(document).ready(function(){

jqu("#related-category li a").click(function(){

    var largePath = jqu(this).attr("href");    
    jqu("#img-preview").attr({ src: largePath });
    return false;
    
});

    jqu("a.next").click(function(){
    jqu(" li.photo").next("a");
});
    jqu("a.prev").click(function(){
    jqu("li.photo").prev("a");
});
});

I've been looking for a solution, but most of the slider images are preload as the slider load while mine doesn't.


Solution

  • The .next() and .prev() methods don't cause a click to happen, they create a jQuery object that contains the next or previous element at the same level in the DOM as the current one. So jqu("li.photo").next("a") won't find anything because there is no anchor at the same level as the li elements, and in any case "li.photo" selects all of the li elements.

    I'd suggest you set a flag (use a class) on the clicked li to remember which one it is, and then you can use .next() and .prev() from that element:

    jqu("#related-category li a").click(function(){
        jqu("#related-category li").removeClass("selected");
        jqu(this).parent().addClass("selected");
        var largePath = jqu(this).attr("href");    
        jqu("#img-preview").attr({ src: largePath });
        return false;    
    });
    
    jqu("a.next").click(function(){
        jqu("li.selected").next().find("a").click();
    });
    jqu("a.prev").click(function(){
        jqu("li.selected").prev().find("a").click();
    });
    

    Demo: http://jsbin.com/iruyap/1/edit

    (Note: you may like to add some code to the prev and next handlers to do something if there is no previous or next item.)