jqueryjquery-uidrag-and-dropsnap-to-grid

onclick clone() a draggable at x&y=0 of the containment to avoid any offset


I'm trying to do something similar to this jsFiddle but instead of dropping manually the widget on the containment I would like to click the widget and the widget goes automatically on the x=0 and y=0 of the containment. And of course then be able to drag and drop (but for that this code works well).

The reason behind this is I want to avoid any grid offset. So once I get x=0 and y=0 I can trust my grid inside the containment by doing:

if (ui.draggable[0].id) {
                        $(this).append($(ui.helper).clone().draggable({
                        grid: [ 40, 40 ],   
                            containment: "#builder",                          
                        }));

                    } 

I have double checked on google it seems to be impossible to snap a grid that would begin by the x=0 and y=0 of the containment. There will always be an offset due to the web architecture of the page. but if you have a solution, I'm taking it !


Solution

  • To make this work you can attach a click handler to the widgets that clones and appends them to #builder manually. To make them appear in the top left by default you simply need to set position: relative in the CSS of #builder, then specify the positioning of the clone before it's appended:

    $widgets.click(function() {
      $('#builder').append($(this).clone().removeAttr('id').css({
        position: 'absolute',
        top: 0,
        left: 0
      }).draggable({
        containment: "#builder",
        scroll: false
      }));
    });
    

    Updated example

    You should however note that there are a lot of issues you need to address in this code: