Search code examples
jqueryjquery-ui-draggablejquery-ui-droppable

jQuery Draggable and droppable prevent ondrop event when on other draggable


I have 3 draggable, blue divs and 1 droppable red div. I want to trigger on drop event when I drag blue div onto red one and at the same time the place it would take is "free", there is no other red div in this area. Screens will be better to describe it:

Triggered on drop: triggered

Not triggered on drop:not-triggered

I don't have idea how to achieve that.

My code:

	$(document).ready(function(){
    	$(".draggable").draggable({
    		drag: function(event,ui){
    				 $(this).css("opacity", .5)
    		}
    	});
    	$('#droppable').droppable({
    		accept: ".draggable",
    		tolerance:  'pointer',
    		drop: function(event,ui){
    		alert("dropped");
    		}
    	});
    });
 	div {
    		margin: 5px;
    	}
    .draggable {
    		width:100px;
    		height: 100px;
    		background-color: blue;
    }
    #droppable {
    		 width: 400px;
    		 height: 400px;
    		 background-color: red;
    }
 <!DOCTYPE html>
    <html lang="en">
    	<head>
    		<title>Bootstrap Example</title>
    		<meta charset="utf-8"> 
    		<meta name="viewport" content="width=device-width, initial-scale=1">
    		<link type="text/css" rel="stylesheet" href="stylesheet.css"/>
    		<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
    		<script src="https://code.jquery.com/jquery-1.12.4.js"></script> 
            <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> 
        
    
    	</head>
    	<body>
    		<div class="container">
    			<div class="row">
    				<div class="col-md-10 col-md-offset-2">
    					<div class="draggable"></div>
    					<div class="draggable"></div>
    					<div class="draggable"></div>
    					<div id="droppable"></div>
    				</div>
    			</div>
    		</div> 
    	</body>
    </html>


Solution

  • You could use a variable to store whether it is free to drop, and change this variable when you drag the blue divs over each other.

        $(document).ready(function(){
        var isFreeToDrop = true;
    
        $(".draggable").draggable({
            drag: function(event,ui){
                     $(this).css("opacity", .5)
            }
        });
    
            $(".draggable").droppable({
              tolerance: 'touch',
            over: function(event,ui){
              isFreeToDrop = false;
            },
            out: function(event,ui){
              isFreeToDrop = true;
            },
    
        });
    
        $('#droppable').droppable({
            accept: ".draggable",
            tolerance:  'pointer',
            drop: function(event,ui){
              if( isFreeToDrop ){
                   alert("dropped");
              }
    
            }
        });
    });
    

    Here is the working version on JSBin: https://jsbin.com/donusajoba/edit?html,css,js,output