How to make jQuery draggable with fixed X and Y axis?

Fred Bergman picture Fred Bergman · Oct 15, 2009 · Viewed 32.5k times · Source

I am wondering if there is a way to make the jQuery draggable to only drag straight up, down and left, right. I want to prevent the user from dragging a div diagonally. Using the grid option in the draggable UI is not possible in my situation.

http://jqueryui.com/demos/draggable/#constrain-movement

How is this possible?

Thanks!

Answer

mobilemonkey picture mobilemonkey · Aug 19, 2013

jQueryUI supports two methods for controlling dragging on a fixed track.

  1. You can use the axis option to limit dragging movement on a particular axis. For instance:

    $('.draggable_horiz').draggable({axis: "x"});
    

    More Info here: http://api.jqueryui.com/draggable/#option-axis

  2. You can constrain movement using an element or an array of x/y coordinates that define a bounding box.

        $('.draggable_track').draggable({ containment: [0,0, 250, 24] });
    
    or to just use the parent element as a reference track:
    
        $('.draggable_track').draggable({ containment: 'parent' });
    

    More info here: http://api.jqueryui.com/draggable/#option-containment

I hope this helps.