morgi
morgi

Reputation: 1025

Drag an image within a div with left/right constraints

I'm trying to nest an image in a div and make it draggable on the X axis within this div.

Here's a jsFiddle to illustrate my point

I'd like the blue box to stop dragging once the user reaches its left/right edges, he shouldn't be able to see any of the red wrapper anymore.

Imagine the blue box is a very wide image, I want to be able to drag it from its left side to its right side without exceeding its width. It means you can't drag it to the right when you reached its left edge, and you can't drag it to the left when you reached its right side.

In a nutshell, when you reach the edges of the image, you can't drag it any more.

How can I set that kind of behavior ?

I tried playing with containment but I couldn't achieve what I wanted.

Thanks for your help.

HTML :

<div id="wrapper">
    <p id="timeline"><img src="" alt="Timeline" width="2000" height="400"/></p>    
</div>

CSS :

#wrapper {
    width: 800px;
    height: 400px;
    background-color : red;
    overflow: hidden;
    cursor: w-resize;
}

#timeline {
    width: 2000px;
    height: 400px;
    margin: 0 auto;
    background-color: blue;
}

JS :

$("#timeline").draggable({
    axis: "x"
});

Upvotes: 3

Views: 6105

Answers (1)

TJ VanToll
TJ VanToll

Reputation: 12704

You were correct to use the containment option but you'll want to pass in array of coordinates to constrain the draggable.

Per the jQuery UI docs the containment option can take an Array in format [x1, y1, x2, y2]. In your case the y values are irrelevant because you are already constraining the draggable to the x axis, so you can simply pass in 0.

For the x values 0 will work for x1 since the image is already starting on the right edge. For x2 you'll need to use:

(width of parent - width of image)

So

(800 - 2000) = -1200

Therefore you can pass the following in for the containment option:

containment: [-1200, 0, 0, 0]

Live Example - http://jsfiddle.net/LMXLj/

Upvotes: 2

Related Questions