Home > Enterprise >  Drop event not firing even with event.preventDefault on dragenter and dragover
Drop event not firing even with event.preventDefault on dragenter and dragover

Time:10-01

I'm struggling to get ondrop event firing. It doesn't fire even when calling event.preventDefault on dragenter and dragover. Actually only onDragEnter it's being fired.

style

.drop_zone {
 border: 5px black dashed;
 width: 300px;
 height: 200px;
}
 HTML
<body>
    <div class="drop_zone" 
        ondragenter="onDragEnter(event)"
        ondragover="onDragOver(event)"
        ondrop="onDrop(event)" >
        <p>Drag one or more files to this Drop Zone ...</p>
    </div>
    <script src="./index.js"></script>
</body>
javascript
function onDrop(e){
    e.preventDefault();
}

function onDragEnter(e){
    e.preventDefault();
}

function onDragOver(e){
    e.preventDefault();
}

CodePudding user response:

$(document).ready(function() {
    var holder = document.getElementById('holder');
    holder.ondragover = function () { this.className = 'hover'; return false; };
    holder.ondrop = function (e) {
      this.className = 'hidden';
      e.preventDefault();
      var file = e.dataTransfer.files[0];
      var reader = new FileReader();
      reader.onload = function (event) {
          document.getElementById('image_droped').className='visible'
          $('#image_droped').attr('src', event.target.result);
      }
      reader.readAsDataURL(file);
    };
});
.holder_default {
    width:500px; 
    height:150px; 
    border: 3px dashed #ccc;
}

#holder.hover { 
    width:400px; 
    height:150px; 
    border: 3px dashed #0c0 !important; 
}

.hidden {
    visibility: hidden;
}

.visible {
    visibility: visible;
}
<!DOCTYPE html>

<html>
    <head>
        <title> HTML 5 </title>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.js"></script>
    </head>
    <body>
      <form method="post" action="http://example.com/">
        <div id="holder" style="" id="holder" class="holder_default">
          <img src="" id="image_droped" width="200" style="border: 3px dashed #7A97FC;" class=" hidden"/>
        </div>
      </form>
    </body>
</html>

CodePudding user response:

thanks for your help.

Actually the event it is being fired. It's a console bug. I set a debugger and a breakpoint within the onDropHandler method but it didn't hit them. But if I use a console.log as below it show me object.

function onDrop(e){
    console.log(e);
    console.log(e.dataTransfer.files[0])
    e.preventDefault();
}
  • Related