jerome
jerome

Reputation: 4977

Set variable on drop using jquery draggable/droppable

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!

Upvotes: 0

Views: 7234

Answers (3)

Pifon
Pifon

Reputation: 356

After the line drop: function(ev, ui) { add:

var droppedId = ui.draggable.attr("id");

After that droppedId will be one of your div0, div1, or div2 - depending on which was dropped.

Upvotes: 0

mohamadfikri
mohamadfikri

Reputation: 121

<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

Upvotes: 2

bendewey
bendewey

Reputation: 40235

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', '');

Upvotes: 0

Related Questions