views:

716

answers:

1

I have a few functions which I load in the ready() event. These basically make a list draggable, and other areas droppable/sortable. Eg. You can drag a clone into multiple areas (lists in divs), and within these multiple areas, you can sort/reorder them (but only within each area). This works perfectly.

I have a button which dynamically creates a new area for items to be dropped into, then sorted. It creates the new area perfectly, but you cannot drop items into it, or then even make them sortable.

I realise this is something to do with the fact I am making all areas droppable/sortable upon page load using the ready() event, and not actually re-running these functions dynamically.

I have tried using 'refresh' on these elements inside the button's click function. Eg.

$(".field > li").draggable('refresh');
$(".dragrow1, .dragrow2").droppable('refresh');
$(".dragrow1, .dragrow2").sortable('refresh');

But this doesn't work. I want to avoid repeating my code in any way if I can help it. Is there a way of making this work? I thought that if there was something similar to the 'live()' function that you can use with 'ready()', then that might be a solution, but there's not...!

Thanks.

+1  A: 

Why not code your initialization as your own jQuery add-on? Then your initialization code as well as the code that adds dynamic elements can just set things up that way.

jQuery(function() {
  jQuery.fn.myDroppableSetup = function myDroppableSetup() {
    this.each(function() {
      // your setup code here
    });
    return this;
  };
  jQuery.fn.myDraggableSetup = // ...
});

Then you can just re-use that when you add things dynamically:

$('div.newlyAddedDroppable').myDroppableSetup();
Pointy
Thanks for the response :) I actually figured out something else that did a similar thing. I create a function to set up droppables, etc. Then I run the function in ready() event. And also run the function whenever I create a new element with my button. But this looks to be a more elegant solution :)Many thanks!
WastedSpace