Drag and Drop using Javascript

Language
In this tutorial, we are going to learn how to the image into the box using javascript. This is a simple project that you can use in your website or system.

DIRECTIONS

HTML CODE

  1. <div id="container">
  2. <p>Drag Image into the squares using HTML5</p>
  3. <div id="left">
  4. <div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
  5. <br>
  6. <div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
  7. <br>
  8.  
  9. </div>
  10. <img id="drag1" src="drag.png" draggable="true" ondragstart="drag(event)" width="150">
  11. <div id="right">
  12. <div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
  13. <br>
  14. <div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
  15. <br>
  16.  
  17. </div>
  18. </div>

JAVASCRIPT CODE

  1. <script>
  2. function allowDrop(ev) {
  3.     ev.preventDefault();
  4. }
  5.  
  6. function drag(ev) {
  7.     ev.dataTransfer.setData("text", ev.target.id);
  8. }
  9.  
  10. function drop(ev) {
  11.     ev.preventDefault();
  12.     var data = ev.dataTransfer.getData("text");
  13.     ev.target.appendChild(document.getElementById(data));
  14. }
  15. </script>

CSS CODE

  1. <style>
  2. #div1 {width:150px;height:150px;padding:10px;border:1px solid #aaaaaa;}
  3.  
  4. #left
  5. {
  6.         border: 1px solid #aaaa;
  7.         width: 200px;
  8.         float: left
  9.        
  10. }
  11.  
  12. #right
  13. {
  14.         border: 1px solid #aaaa;
  15.         width: 200px;
  16.         float: right;
  17.        
  18. }
  19. #container
  20. {
  21.         width: 580px;
  22.         margin: auto;
  23. }
  24. p
  25. {
  26.         font-size: 25px;
  27.         text-align: center;
  28. }
  29. </style>
Share your thoughts in the comment section below or email me at [email protected]. Practice Coding. Thank you.

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Add new comment