030.html (2312B)
1 <!doctype html> 2 <html> 3 <head> 4 <title>Drag and drop without cancelling dragenter on body</title> 5 <style type="text/css"> 6 div:first-child { 7 height: 100px; 8 width: 100px; 9 background: orange; 10 display: inline-block; 11 } 12 div:first-child + div { 13 height: 100px; 14 width: 100px; 15 margin-left: 100px; 16 background: blue; 17 display: inline-block; 18 } 19 </style> 20 <script type="text/javascript"> 21 //If dragenter is cancelled the body should then become the target element, receiving both a dragenter and a dragover event. 22 //When the body is the actual immediate user selection (first time over the body), that means it gets *2* dragenter events 23 //Then when a div becomes immediate user selection (blue) but does not cancel the dragenter event, dragenter does not need 24 //to fire on body because body is already the current target element 25 //Then when the body is the actual immediate user selection again (second time over the body), it is already the current 26 //target element, so does not get a dragenter event 27 window.onload = function () { 28 var drag = document.getElementsByTagName('div')[0], beforecount = 0, aftercount = 0, switchcount = false; 29 drag.ondragstart = function (e) { 30 e.dataTransfer.setData('text','hello'); 31 e.dataTransfer.effectAllowed = 'copy'; 32 }; 33 drag.ondragenter = drag.ondrop = drag.ondragover = function (e) { 34 e.preventDefault(); 35 }; 36 var drop = document.getElementsByTagName('div')[1]; 37 drop.ondragenter = function (e) { 38 switchcount = true; 39 }; 40 drop.ondragover = function (e) { 41 e.preventDefault(); 42 }; 43 document.body.ondragenter = function (e) { 44 if( e.target != this ) { return; } 45 if( switchcount ) { aftercount++; } else { beforecount++; } 46 }; 47 drag.ondragend = function (e) { 48 document.getElementsByTagName('div')[2].innerHTML = ( beforecount == 2 && aftercount == 0 ) ? 'PASS' : ( 'FAIL, dragenter fired on body '+beforecount+' time(s) before blue.ondragenter and '+aftercount+' time(s) afterwards, instead of 2 and 0 times respectively' ); 49 }; 50 }; 51 </script> 52 </head> 53 <body> 54 55 <div draggable="true"></div><div></div> 56 <div> </div> 57 <p>Drag the orange square onto the blue square, then back to the orange square, and release it.</p> 58 <noscript><p>Enable JavaScript and reload</p></noscript> 59 60 </body> 61 </html>