I'm creating an drag and drop plugin and I thought to make it a little unique i would add a cookies feature to save the position of the dragged elements.
I'm currently using the following code for the get and set cookies:
$.setCookie = function(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
$.getCookie = function(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
These work fine. But What I can't get to work is this:
if (o.cookies === true) {
$(oj).mouseup(function() {
var currentPos = $(oj).position();
$.setCookie('tposition22' + $(oj).index(), currentPos.top, 365);
$.setCookie('lposition22' + $(oj).index(), currentPos.left, 365);
alert('Cookies Set!')
});
$(function() {
var savedLeftPosition = $.getCookie('lposition22' + $(oj).index());
var savedTopPosition = $.getCookie('tposition22' + $(oj).index());
$(oj).css({
top: savedTopPosition,
left: savedLeftPosition
});
});
}
Code Description: o.cookies === true
is to check if cookies is set to true; setCookie works(I checked); oj
is referring to this
, the selector.
Problem: I need to be able to get the value of the cookie. Because, im currently trying to make the value the position of the dragged element and then retrieving it.
As you can see in $.setCookie('tposition22' + $(oj).index(), currentPos.top, 365);
, currentPos.top
is in the value spot. To get the Y position of the dragged element.
Main Question: Is there a way to retrieve the value
of a cookie?
Sure you can retrieve the value of a cookie. I like not reinventing the wheel, though, and since you're already in jQuery-ville, why not use a jQuery cookie plugin? I think there's even an "official" one. Should provide simple access to everything you need for interacting with cookies (really, just getting and setting one!).
With regard to your specific code, where is o
(from o.cookies
) coming from, and why is it expected to be a boolean?
Side note: almost all code can benefit from properly-named variables. Letting your minifier reduce down to single-letter will keep your code more readable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With