sashomaga

Drag and drop

May 9th, 2013
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <!DOCTYPE html>
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4.     <title></title>
  5. </head>
  6. <body>
  7.     <img src="close.png" ondrop="handleDrop(event)" ondragover="handleDragOver(event)" ondragleave="handleDragLeave(event)"/>
  8.     <script>
  9.         'use strict';
  10.  
  11.         (function () {
  12.             var trashCanHeight = 450;
  13.             var trashCount = 10;
  14.             var documentFragment = document.createDocumentFragment();
  15.  
  16.             for (var i = 0; i < trashCount; i++) {
  17.                 var trash = document.createElement('img');
  18.                 trash.style.position = 'absolute';
  19.                 trash.style.top = getRandomPosition(trashCanHeight, screen.height - 250) + 'px';
  20.                 trash.style.left = getRandomPosition(0, screen.width - 250) + 'px';
  21.                 trash.setAttribute('id', i);
  22.                 trash.setAttribute('src', 'trash.png');
  23.                 trash.setAttribute('draggable', 'true');
  24.                 trash.setAttribute('ondragstart', 'handleDragStart(event)');
  25.                 trash.setAttribute('ondragend', 'handleDragEnd(event)');
  26.  
  27.                 documentFragment.appendChild(trash);
  28.             }
  29.             document.body.appendChild(documentFragment);
  30.  
  31.             function getRandomPosition(start, end) {
  32.                 var random = Math.floor((Math.random() * (end - start) + start));
  33.                 return random;
  34.             }
  35.         }());
  36.  
  37.         function handleDragStart(e) {
  38.             e.dataTransfer.setData("dragged-id", e.target.id);
  39.             e.target.style.opacity = '0.5';          
  40.         }
  41.  
  42.         function handleDragOver(e) {
  43.             e.preventDefault();
  44.             e.target.setAttribute('src', 'open.png');
  45.         }
  46.  
  47.         function handleDragLeave(e) {
  48.             e.target.setAttribute('src', 'close.png');
  49.         }
  50.  
  51.         function handleDragEnd(e) {          
  52.             e.target.style.opacity = '1';
  53.         }
  54.  
  55.         function handleDrop(e) {
  56.             e.preventDefault();
  57.             var trashId = e.dataTransfer.getData("dragged-id");      
  58.             var trashNode = document.getElementById(trashId);
  59.             trashNode.parentNode.removeChild(trashNode);
  60.         e.target.setAttribute('src', 'close.png');                  
  61.         }
  62.     </script>
  63. </body>
  64. </html>
Advertisement
Add Comment
Please, Sign In to add comment