Search code examples
jqueryjquery-uidrag-and-dropjquery-ui-draggablejquery-ui-droppable

How to run a droppable function more than once


So far I have two images(one man and one woman) that are draggable. When I drag the man, I want the droppable image to change to a man and same for the woman. So far it works, but let's say I already changed the droppable image to a man. Then when I drag the woman over, it will not switch to an image of a woman. It only sticks to the first image that it changes to and I want the user to be able to drag and change the image multiple times.

    <div class="types">
    <h1>TWO TYPES OF HARRASSMENT</h1>
    <p>Click and drag the employees to reveal more information.</p>
    <img class="draggable-woman" src="images/drag-woman.png" />
    <img class="draggable-man" src="images/drag-man.png" />
    </br>
    <div class="types-child">
        <img class="quid" src="images/quid-empty.png" />
        <div class="changeable-text"></div>
        <img class="hostile" src="images/hostile-empty.png" />
    </div>
</div>

<script>
$(".draggable-woman").draggable({
    helper: "clone"
  });
  $(".draggable-man").draggable({
    helper: "clone"
  });
$(".quid").droppable({
    drop: function( event, ui ) {
        if ($(ui.draggable).hasClass("draggable-woman")){
        $(this).replaceWith("<img class='quid' src='images/quid-withwoman.png'>");

        } else {
        $(this).replaceWith("<img class='quid' src='images/quid-withman.png'>")
        }
    }
});
</script>

Solution

  • Only need re-handle the events. this could work for you:

    $(".draggable-woman").draggable({
        helper: "clone"
    });
    
    $(".draggable-man").draggable({
    helper: "clone"
    });
    
    function handleQuidClass(){
        $(".quid").droppable({
        drop: function( event, ui ) {
                if ($(ui.draggable).hasClass("draggable-woman")){
                    $(this).replaceWith("<img class='quid' src='images/quid-withwoman.png'>");
                } else {
                    $(this).replaceWith("<img class='quid' src='images/quid-withman.png'>")
                }
                handleQuidClass();
            }
        });
    }
    
    handleQuidClass();