views:

2229

answers:

2

I am working on a proof of concept that makes use of the jquery ui draggable/droppable.

I am looking for a way to set a variable equal to the index of a div that is dropped into the droppable area. (Say I have divs named "div0", "div1", "div2", etc...)

So imagine the code would look something like this:

<div id="div0" class="draggableDiv">some cotent</div>
<div id="div1" class="draggableDiv">more content</div>
<div id="div2" class="draggableDiv">yet more content</div>

<div class="droppableDiv">drop it here</div>

$(document).ready(function() {
    $('.draggableDiv').draggable({helper: 'clone'});
    $('.droppableDiv').droppable({
     accept: '.draggableRecipe',
     drop: function(ev, ui) { 
      ui.draggable.clone().fadeOut("fast", 
      function() { 
       $(this).fadeIn("fast") 
      }).appendTo($(this).empty());
                        // function to set someVar = div[index];
     }
    });
});

I am not sure how best to accomplish this, so if anyone has any suggestions, I'd appreciate some guidance.

Thanks!

A: 

You should be able to parse the id of the div by using

$.droppedItems = {};

var droppedId = $(this).attr('id').replace('droppable', '');
$.droppedItems[droppedId] = ui.draggable.attr('id').replace('div', '');
bendewey
Ah, thanks. So now imagine that I have multiple divs with class="droppableDiv", so say id="drop0", id="drop1", id="drop2". How could I associate the currentIndex of the draggable div with the index of the droppable div? If $(this) refers to the draggable how do I refer to the droppable?
jerome
updated the post. I may have been mistaken about the use of this on the droppable.
bendewey
+1  A: 
<div id="div0" class="draggableDiv">some cotent</div>
<div id="div1" class="draggableDiv">more content</div>
<div id="div2" class="draggableDiv">yet more content</div>

<div id='dropplace' class="droppableDiv">drop it here</div>

<script language='javascript'>

$(document).ready(function() {
    $('.draggableDiv').draggable({helper: 'clone'});
    $('.droppableDiv').droppable({
        accept: '.draggableDiv', //changed this, it was originally 'draggableRecipe'
        drop: function(ev, ui) { 

                //get the index of dropped draggable div
             var divIndex = $('div').index(ui.draggable)
                alert(divIndex) //alert the divIndex to see the result

                ui.draggable.clone().fadeOut("fast", 
                function() { 
                        $(this).fadeIn("fast") 
                }).appendTo($(this).empty());
        }
    });
});
</script>

Tested this one, it works for me and hope will work for you too. good luck

mohamadfikri