syddiecat
syddiecat

Reputation: 1

Remember position of a div on refresh?

I am using a code that allows for a div to be moved on click wherever the user wants to on the page. http://api.jqueryui.com/draggable/

What I want to do, however, is for the browser/webpage to remember where the user dragged the cbox to so it will stay there after refreshing the page. Right now, if you move it, when you refresh it puts it back to where it started. I figured this is done via cookies but I can't think of where to start to accomplish this.

http://candyland-couture.com The chat box on the bottom left is the moveable div I'm referring to. It is draggable by hovering over the purple banner above it and clicking and dragging.

Upvotes: 0

Views: 2071

Answers (2)

Hackerman
Hackerman

Reputation: 12295

You could use a function like this one, to save the coordinates to a cookie:

$("#moveme").draggable({
  // Find position where element is dropped.
  stop: function(event, ui) {
    // Show dropped position.
    var Stoppos = $(this).position();
    console.log("STOP: \nLeft: "+ Stoppos.left + "\nTop: " + Stoppos.top);
    //Save the values to cookie o localStorage
    //I'm gonna use jquery cookie plugin
    $.cookie("left",Stoppos.left);
    $.cookie("top",Stoppos.top);
  }
});

Then when you refresh the page, if those cookies exists and their values are not empty, you set the values on your element:

$("#moveme").css({top: $.cookie("top"), left: $.cookie("left")});

You should include the plugin in your website, so here it is: https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.js

Upvotes: 1

David Gomes
David Gomes

Reputation: 5835

Use localStorage. Save the coordinates of the div (top and left perhaps) inside it. Another option would be cookies but for something this simple localStorage might be the better fit.

Upvotes: 1

Related Questions