Changing the image source of a droppable with a draggable image

2.3k views Asked by At

I have a <div> containing the three images with the class "droppable". The table has four rows with the image inside the last <td> element.

The HTML looks like this:

<div id="box_container">
  <img id="empty_box1" class="droppable" src="images/tom.png" />
  <img id="empty_box2" class="droppable" src="images/tom.png" />
  <img id="empty_box3" class="droppable" src="images/tom.png" />
</div>

<td><img id="" class="draggable" src="images/image1.png" /></td>

Following is a picture of how the layout looks like below:

enter image description here

The images in the table are draggable into the empty boxes above the table. The boxes consists of an image of white space and I want the source of that image to change to the image that has been dropped into the empty box.

Below is my code at the current stage:

$(document).ready(function () {
  $(".draggable").draggable({
    revert: true,
    snap: ".droppable",
    snapMode: "inner"
  });
  $("#tabellen").tablesorter();
  $(".droppable").droppable({
    accept: ".draggable",
    drop: function () {
        console.log(this);
        var new_pic = $('.draggable').attr('src');
        $(this)
            .attr('src', new_pic)
            .attr('width', 150)
            .attr('height', 150)
            .addClass('zoomable');
    }
  });
});
1

There are 1 answers

0
T J On BEST ANSWER

Inside the drop event callback, you can access the dropped draggable element via the draggable property of second argument (Commonly named as ui). You can copy it's source to droppable as shown below:

$(".draggable").draggable({
  helper: "clone",
  revert: "invalid"
});
$(".droppable").droppable({
  drop: function(event, ui) {
    $(this).attr("src", ui.draggable.attr("src"));
  }
});
img {
  width: 100px;
  height: 100px;
}
.draggable {
  background: hotpink;
  float: left;
}
.droppable {
  float: right;
  background: dodgerblue;
}
<link href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<img class="draggable" src="http://i49.tinypic.com/28vepvr.jpg" />
<img class="droppable" src="" alt="Drop Here!" />