/ Gists / Drag drop
On gists

Drag drop

JavaScript

demo.html Raw #

<!-- https://jsbin.com/rideqiloge/edit?html,output -->

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Drag and Drop Effect in JavaScript</title>

    <!-- Add some CSS Code -->
    <style>
      * {
        margin: 0px;
        padding: 0px;
      }
      body {
        background-color: black;
        height: 100vh;
        width: 100%;
      }
      .container {
        display: flex;
        justify-content: space-around;
        align-items: center;
        flex-wrap: wrap;
        height: 100vh;
        width: 100%;
      }
      .whiteBox {
        width: 150px;
        height: 150px;
        background-color: white;
        border: none;
        border-radius: 50%;
      }
      .imgBox {
        background: url("https://images.unsplash.com/photo-1469474968028-56623f02e42e?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=874&q=80") no-repeat center center;
        height: 100%;
        width: 100%;
        background-size: cover;
        border: none;
        border-radius: 50%;
        cursor: pointer;
        display: grid;
        place-items: center;
      }
      .hold {
        border: 4px solid white;
      }
      .hide {
        display: none;
      }
    </style>
  </head>
  <body>

    <div class="container">
      <div class="whiteBox" id="box">
        <div class="imgBox" draggable="true"></div>
      </div>
      <div class="whiteBox" id="box"></div>
      <div class="whiteBox" id="box"></div>
      <div class="whiteBox" id="box"></div>
      <div class="whiteBox" id="box"></div>
    </div>

    <!-- Let's start to write script -->
    <script>

      // Access the HTML Elements
      let imgBox = document.querySelector(".imgBox");
      let whiteBoxes = document.getElementsByClassName("whiteBox");


      // When user start to drag the element ( Here, imgBox )
      // Event listeners for dragable imgBox element
      imgBox.addEventListener("dragstart", (e) => {

        e.target.className += " hold";
        setTimeout(() => {
          e.target.className = "hide";
        }, 0);
      });

      // When user ready to drop the element 
      imgBox.addEventListener("dragend", (e) => {
        e.target.className = " imgBox";
      });

      // Iterate all the white boxes
      for (Boxes of whiteBoxes) {
        Boxes.addEventListener("dragover", (e) => {
          e.preventDefault();
        });

        Boxes.addEventListener("drop", (e) => {
          e.target.append(imgBox);
        });
      }
    </script>
  </body>
</html>