Search code examples
jqueryjquery-uidraggable

JQuery draggable and scrolling in a div with fixed height


I have been struggling to find the answers to what should be a simple task. I want to stack images on top of each other (all the same width) inside a div with a fixed height. Simple. But as well as being able to use the container div's scrollbar to scan up & down the images, I would also like the JQuery draggable widget to allow the user to grab and slide the image stack up and down as well.

The issues I am having are:

  1. Dragging and scrolling do not seem to be linked so the image wrapper div position doesn't match the scrollbars of the container div.
  2. I would like to stop the last image being scrolled above the bottom of the wrapper, likewise, stop the top image being dragged below the top. Containment doesn't work here as the content is larger than the container.

I have tossed a quick fiddle together here: http://jsfiddle.net/QhWbm/

// HTML
<div id="wrapper">
    <div id="scroller">
        <img src="http://placekitten.com/200/100" width="200" height="100" />
        <img src="http://placekitten.com/200/200" width="200" height="200" />
        <img src="http://placekitten.com/200/150" width="200" height="150" />
        <img src="http://placekitten.com/200/250" width="200" height="250" />
    </div>
</div>

// JS
$(document).ready(function(){
    $("#scroller").draggable({
        axis:"y"        
    });
});

// CSS
#wrapper {
    width: 220px;
    height: 200px;
    overflow: auto;
    border: 1px solid #ff0000;
}

A quick play will show the disconnect between dragging and scrollbar, and the ability to drag off the top/bottom.

Any advice would be fantastic, many thanks


Solution

  • The dragscrollable jQuery plugin will do what you're looking for

    $('#wrapper, #scroller').dragscrollable({
        dragSelector: 'img', 
        acceptPropagatedEvent: false
    });
    

    http://jsfiddle.net/QhWbm/1/

    I couldn't find it anymore on jQuery's plugin site but there are several mirrors of it on the web.

    See also: How to drag and scroll in a div with jQuery