Question

I have a script that selects and drags several elements. It works fine but when I want to add another new element to that function, append it to DOM, it does not work. The function is:

$(function() {
        var selected = $([]), offset = {top:0, left:0};
        $("#selectable1").selectable();

        $("#selectable1 span").draggable({
            start: function(ev, ui) {
                $(this).is(".ui-selected") || $(".ui-selected").removeClass("ui-selected");

                $("span").removeClass("cica"); // ads class Cica to the draged/selected element
                $(this).addClass("cica");

                selected = $(".ui-selected").each(function() {
                    var el = $(this);
                    el.data("offset", el.offset());
                    $(this).text("Selected and dragging object(s)");
                });

                offset = $(this).offset();
            },
            drag: function(ev, ui) {
                var dt = ui.position.top - offset.top, dl = ui.position.left - offset.left;
                selected.not(this).each(function() {

                    var el = $(this), off = el.data("offset");
                    el.css({top: off.top + dt, left: off.left + dl});

                });

            },
            stop: function(ev, ui){
                $(this).text("Drag has stopped");
            }
        });
    });

The new element is added like this:

$('<span class="drag">Xia</span>').appendTo('#selectable1');

I know that I can use live to make it work but I do not know where to add it in the script. I only know how to add it on a event like click, mouseover.

Please let me know if you have some tips on this one.

Thank you

Was it helpful?

Solution

What I'd do is to set up "#selectables1" with an event handler for a made-up event called "dragSetup". That would look something like this:

$('#selectables1').bind('dragSetup', function() {
  $(this).find('span:not(.dragReady)')
    .draggable({ ... })
    .addClass('dragReady');
});

Then whenever you add a new you can just call:

$('#selectables1').trigger('dragSetup');

OTHER TIPS

You have to use live to attach the events to the DOM elements that are added once the DOM is loaded. jQuery Doc for live

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top