hey guys,
I can’t seem to get it working. I have draggable black bars that act as navigation on top of the content.
I simply want to browser to remember the position of the bars with a cookie. Whenever a user drags the bars and clicks something else (the page refreshes) the bars should stay at the last position.
I can’t seem to get it working. Moreover I wish to have a simple random distribution of the bars when a user visits the site for the first time.
I’ve built a quick example. Maybe you know what I’m doing wrong here: http://jsfiddle.net/RZQ8H/
$("ul.bars li").draggable({
stop: function(event, ui) {
var currentPos = $(this).position();
var currentTop = Math.round(currentPos.top);
// save cookie when stopped dragging
$.cookie('position' + $(this).index('li').toString(), currentTop.toString());
}
});
The position when the page is loaded…
// initial position of elements
$("ul.bars li").each(function() {
// if no cookie is set (first visit to page) all bars should be distributed
// randomly across the document
if ( $.cookie('position'+ $(this).index('li').toString()) ) {
var doc = $(document).height() - 50;
// random distribution of elements
$("ul.bars li").each(function() {
var randPos = Math.random(0)*doc;
$(this).css('top' , randPos+'px');
});
} else {
// if a cookie exists (the bars have already been dragged)
// remember the position
var savedPos = $.cookie('position' + $(this).index('li').toString());
$(this).css({ top: savedPos + 'px' });
}
});
You got your condition wrong way around:
Swap it around, so that if a cookie exists, it won’t randomly distribute them.
Example:
http://fiddle.jshell.net/RZQ8H/3/show/