I am currently using this code that works wonderfully:
$(document).ready(function () {
if ($.cookie("cvispos") != undefined) {
var unwrapped = window.JSON.parse($.cookie("cvispos"));
var left = window.JSON.parse($.cookie("cvispos")).left;
var top = window.JSON.parse($.cookie("cvispos")).top;
$("#cguts").css("left", left + "px");
$("#cguts").css("top", top + "px");
}
});
// Buncha cookie stuff and onclick trash...
$("#cguts").draggable({
stop: function (event, ui) {
$.cookie("cvispos", window.JSON.stringify(ui.position));
}
The problem I am having is that if you drag the box to far up or down, you are able to move it off the screen entirely without the ability to move it back. Is there a way to keep it from moving outside of the viewpoint? I tried using snap, but I was unable to get it to work. I could achieve it by setting a min/max on the positioning, but couldn't find any resources that led me to believe it is possible with this code.
You can set the containment
parameter of the draggable to the window
to restrict its movement to within the visible bounds.
Also note that you can optimise your code by only deserialising the JSON once and setting both css()
properties in a single call. Try this:
$(document).ready(function () {
if ($.cookie("cvispos") != undefined) {
var cookieData = JSON.parse($.cookie("cvispos"));
$("#cguts").css({
left: cookieData.left + "px",
top: cookieData.top + "px"
});
}
});
// Buncha cookie stuff and onclick trash...
$("#cguts").draggable({
containment: 'window',
stop: function (event, ui) {
$.cookie("cvispos", JSON.stringify(ui.position));
}
});