I use jQuery UI .droppable for dropping elements to divs. Now I need to prevent dropping to divs with class .box if they are not empty.

if ($('.box').is(':empty')) {
    $(".box").droppable({

    });
}

But this makes all .box divs non-droppable whether they are empty or not.

Hi,
here's a short example on how you would apply it inside an empty div. Only one div has some text inside and this will prevent any changes made by the drop event except from the 3 divs.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style type="text/css">
  .box {
    width: 200px;
    height: 200px;
    background: #000;
    margin-bottom: 50px;
    color: #ff8877;
    text-align: center;
    position: relative;

  }
  .box span {
    display: block;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    font-size: 1.2em;
  }
  .box.bg-grey {
    background: #ddd;
  }
  </style>
</head>
<body>

  <div class="box"></div>
  <div id="boxie" class="box"></div>
  <div class="box"><span>DROP HERE!</span></div>
  <div class="box"></div>

          <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>

        <script type="text/javascript">
        jQuery(document).ready(function($) {
          $(function() {
          $('.box').draggable();
          $('.box').droppable({
            drop: function(event, ui ) {
              $('.box:empty').toggleClass('bg-grey');

            }
          });
        });

        });
        </script>

</body>
</html>

Hope this helps.

Unfortunately, there is no difference among those 4 divs. Dropping works for them all

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.