简体   繁体   中英

How to stop jQuery draggable from dragging it off the screen?

I currently study Bootstrap and RWD in general and I want to build a responsive photo gallery to gain experience in these topics.

I have already built 95% of what I wanted to, except 1 thing.

Basically, I have a group of small images next to each other and when I click on the small image I can see it bigger. This group of images is a jQuery draggable and the problem with that is I can drag it off screen if I want to.

$("#myDraggable").draggable({
    scroll: true,
    axis: "x",
    cursor: "move"          
});

What I see in answers of other similar questions is that people suggest to use scroll: false but that's not what I need since I want to be able to scroll.

I have all the code available on codepen: https://codepen.io/tomsoos/full/WRqeJR/

If you are not familiar with codepen you can click on the Change View button to change between the Editor View and the Full Page.

When you open the code in Full Page and try to drag the group of images off screen you will be able to do that.

My question is how can I prevent that but still be able to drag these images?

use the containment option this will stop the item being dragged out of a container on the page. Where the string passed is a jquery selector. have a look Here at the docs

for example.

  $("#myDraggable").draggable({
    scroll: true,
    axis: "x",
    cursor: "move",
    containment: "body"
 });   

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