views:

153

answers:

2

After making a div draggable, i would like, when the div is dropped, to pass to the controller the div's position so that it can be saved on to the database.

My first idea would be to have an hidden form within the div, with 2 text fields (one for X and one for Y) which is kept updated via javascript and submitted on drop.

However this sounds like a bit of a hack and is not an elegant solution. Has anybody encountered this before?

Thank you.

+3  A: 

You could simply use an AJAX request that would post the X and Y values to your Rails application in the background. No need to store the positions in your HTML.

If you use jQuery you could use something like this:

// Include this in an onDrop event handler:
element = ... // dropped div
url = "http://example.com/.../save_div_position/";
data = $(element).position();
success_callback = function(data, textStatus) {
    // alert that new position is saved
};
$.post(url, data, success_callback, "json");
molf
Thanks - this is very helpful. I was wondering how this could be translated into a more 'rails-y' code. In rails, i'm using prototype but can also switch to jQuery
Stefano
+2  A: 

I was also going to say storing the positions in text fields is a bad idea. jQuery UI provides draggable and is easily used. The example below will send a ajax request whenever the element is dropped.

$('#draggable_element').draggable({  
    stop: function(event, ui) {   
        $.post("http://example.com/some_action",
            { top: ui.position["top"], left: ui.position["left"] },
            function() {  
                // callback stuff
            }
        );
    }  
});
danengle
Thanks, this is also very helpful. How could i write all this using erb in rails?
Stefano
You wouldn't write it all using erb. In one of your html.erb templates, you would just have a div with an ID or class assigned to it (corresponding to the .draggable function) and then in a separate (and included) javascript file, you would have that code inside the jQuery initialize function.
danengle