Search code examples
javascriptjqueryhtmljquery-uidraggable

Change droppable div text based on which draggable item is dropped


Fellow programmers, I have 2 draggable div's with unique id's. I need to change the text on a droppable div to a specific text based on which draggable is dropped.

HTML:

<div id="drag1" class="ui-widget-content">
    <p>Great</p>
</div>


<div id="drag2" class="ui-widget-content">
    <p>Poor</p>
</div>

<div id="droppable" class="ui-widget-header">
    <p>You Chose</p>
</div>    

jQuery code:

$( "#drag1, #drag2" ).draggable();

    $( "#droppable" ).droppable({
    drop: function( event, ui )
    {
        $( this )
        .addClass( "ui-state-highlight" )
        .find( "p" )
        .html(ui.draggable[0].id);
    }
});

Solution

  • I used your code snippet and it seems to work that way. I've added data-info attribute as an option to pass some text to the droppable div.

    $( "#drag1, #drag2" ).draggable();
    
    $( "#droppable" ).droppable({
        drop: function( event, ui ) {
            $(this)
                .addClass("ui-state-highlight")
                .find("p")
                .html($('#'+ui.draggable[0].id).data('info'));
        }
    });
    .ui-widget-content {
        cursor: pointer;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.js"></script>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
    
    
    <div id="drag1" data-info="My great div was chosen" class="ui-widget-content">
        <p>Great</p>
    </div>
    
    
    <div id="drag2" data-info="My poor div was chosen" class="ui-widget-content">
        <p>Poor</p>
    </div>
    
    <div id="droppable" class="ui-widget-header">
        <p>You Chose</p>
    </div>