Question

I have been creating an image gallery with jQuery, all is done. The images are placed side by side horizontally within a div whose overflow id hidden (I don't want to show scrollbars).

I have two images arrow left and arrow right within links. Now I want to do is that when I click left arrow, it should show previous image and when I click right arrow image, it should show next image. I suspect I will have to move scrollbars in the right direction when corresponding arrow image is clicked with jQuery.

How to do that?

Was it helpful?

Solution

I believe you could do this with scrollLeft

$("#leftArrow").click(function(){
    $("#divId").scrollLeft(Math.max(0, $("#divId").scrollLeft() - 100));
});

$("#rightArrow").click(function(){
    $("#divId").scrollLeft(Math.min(1000, $("#divId").scrollLeft() + 100));
});

With appropriate limits instead of 0 and 1000, and your image width instead of 100.


However, looking at your example page, you have another problem.

You think that your images are being placed like this:

    [Visible area]        [ Overflow .... ]
.=========================._ ___ ___ ___         ___
X   |   |   |   |   |   | X |   |   |   | . . . |   |
X___|___|___|___|___|___|_X_|___|___|___|       |___|
"========================="

and that scrolling the visible area horizontally will make the other images become visible.

In fact, the images are being placed like this:

    [Visible area]        
.=========================.
X   |   |   |   |   |   | X
X___|___|___|___|___|___| X
"========================="
|___|___|___|___|___|___|
|   |   |   |   |   |   |
|___|___|___|___|___|___|  [ Overflow ... ]
  ...
 ___ ___ ___ ___ ___ ___
|   |   |   |   |   |   |
|___|___|___|___|___|___|

... so the horizontal scroll does no good. (The images are actually overflowing vertically! In fact, you can see this if you use the same code but with scrollTop instead of the scrollLeft)

The images are wrapping because they are inside a div that has an explicit width.

You can solve this by placing a second div inside your first div (the one with the overflow:none) that is wide enough to accommodate all of your images.

As your page is, executing

javascript:
$("#images")
.css("overflow", "hidden")
.wrapInner("<div style='width:1000px'>");

will do the trick. Then if you execute

javascript:
$("#images").scrollLeft(10);

you will see that the horizontal scroll actually works.

OTHER TIPS

If you want to do a slightly sexier version, you can animate the scrollable area.

$("#left").click(function(){
    $("#scroll-holder").animate({ scrollLeft: Math.max(0, $("#scroll-holder").scrollLeft() - 250)}, 175);
});
$("#right").click(function(){
    $("#scroll-holder").animate({ scrollLeft: Math.max(1000, $("#scroll-holder").scrollLeft() + 250)}, 175);
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top