I found these two very simple draggable div
blocks of code: link1 and link2
How to constrain movement in x-axis to screen width with JS/jQuery without jQuery UI?
I DID SEARCH but I there are only references to jQuery UI.. How to do it yourself?
I found these two very simple draggable div
blocks of code: link1 and link2
How to constrain movement in x-axis to screen width with JS/jQuery without jQuery UI?
I DID SEARCH but I there are only references to jQuery UI.. How to do it yourself?
I'm going to base it off of the first code snippet you linked to.
In order to constrain the div to horizontal movement, all you need to do is remove the part of the code that sets the top
offset!
After that, constraining the div to the boundary of the window takes some thought. The coordinates currently offseting the div (e.pageX + pos_x - drg_w
) correspond to the top-left corner of the div. We never want that to go past the leftmost boundary of the window, or x=0
. A nice way to do this mathematically is with the Math.max
function, which will return the larger of two values.
left: Math.max(e.pageX + pos_x - drg_w, 0)
Now we need to check the right border of the window. We take the coordinate of the right boundary ($(window).width()
) and subtract the width of the div since we're checking the right edge of the div against it. Correspondingly, Math.min
can be used to great effect in this situation.
All together now,
$('.draggable').offset({
left: Math.min($(window).width() - drg_w, Math.max(e.pageX + pos_x - drg_w, 0))
})
And a code pen of those minor changes. :)