Whesley Barnard
Whesley Barnard

Reputation: 309

jQuery UI dragging, update target element

I am trying to develop a page that will allow users to drag an element(like a DIV) to another DIV.

Once the dragged element is over the target div and the user lets go of the mouse, the target div should have something happen to it. For example it should change colour and have some text inserted into it.

So basically what I want is for some how to know that the element has been dropped on the target div so that I can manipulated the target div however I want.

Here is my jsfiddle prototype. http://jsfiddle.net/WhesleyBarnard/3Lnxnc4o/1/ The target div is the big green div.

So to answer my question I only need you guys to help me change the target divs colour and text as soon as the element is dropped on it.

Thanking you in advance.

Current Code Extract
HTML

<div id="div1"><div></div></div>
<div id="div2"></div>

CSS

#div1 {
    height: 100px;
    background-color: red;
    margin-bottom: 50px;
    padding: 5px;
}
#div1 div {
    width: 30px;
    height: 30px;
    border: solid 1px black;
}
#div2 {
    height: 100px;
    background-color: green;
    padding: 5px;
}

jQuery

$(document).ready(function() {
    $('#div1 div').draggable({
        cursor: "none",
        revert: true
    });
});

Upvotes: 0

Views: 650

Answers (1)

T J
T J

Reputation: 43156

You should make your target <div> a droppable element using droppable() method, then you can use the drop event callback to detect when an item is dropped and manipulate the droppable using this keyword:

$(document).ready(function() {
  $('#div1 div').draggable({
    cursor: "none",
    revert: true
  });
   $('#div2').droppable({
     drop:function(){
         $(this).css("background","dodgerblue").text("Something is dropped!")
     }
  });
});
#div1 {
    height: 50px;
    background-color: red;
    margin-bottom: 50px;
    padding: 5px;
}
#div1 div {
    width: 30px;
    height: 30px;
    border: solid 1px black;
}
#div2 {
    height: 50px;
    background-color: green;
    padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.1/jquery-ui.min.js"></script>
<div id="div1"><div></div></div>
<div id="div2"></div>

Upvotes: 2

Related Questions