Search code examples
javascripteventsdrag-and-dropevent-dispatching

HTML5 Drag and Drop ondragover not firing in Chrome


I have this simple example here which is not firing in Chrome 11 for me http://jsfiddle.net/G9mJw/ which consists on a very simple code:

var dropzone = document.getElementById('dropzone'),
    draggable = document.getElementById('draggable');


function onDragOver(event) {
    var counter = document.getElementById('counter');
    counter.innerText = parseInt(counter.innerText, 10) + 1;
}


dropzone.addEventListener('dragover', onDragOver, false);

It seems to work fine in safari tho...but in Chrome the dragover event is not being called when the red square touch the dotted one.

I've tried to replicate some examples which have this currently working in chrome but it din't work for me either.

I've tried prevent the default behaviour to see it if worked but it didn't. any help would be very appreciated.

thanks


Solution

  • It seems that it is needed to set some data to the draggable element on the dragstart event for the dragover event to be fired on the dropzone.

    I've updated the snippet http://jsfiddle.net/G9mJw/20/ which now works in chrome as well.

    and the new code as follows:

    var dropzone = document.getElementById('dropzone'),
        draggable = document.getElementById('draggable');
    
    
    function onDragStart(event) {
        event.dataTransfer.setData('text/html', null); //cannot be empty string
    }
    
    function onDragOver(event) {
        var counter = document.getElementById('counter');
        counter.innerText = parseInt(counter.innerText, 10) + 1;
    }   
    
    draggable.addEventListener('dragstart', onDragStart, false);
    dropzone.addEventListener('dragover', onDragOver, false);
    

    Also there's some more information about how this works at: https://developer.mozilla.org/En/DragDrop/Drag_Operations#Drag_Data and this mention things like:

    When a drag occurs, data must be associated with the drag which identifies what is being dragged.

    Which make easier to understand... I am just trying to figure out how does this works in Safari without the need to send some data? or perhaps it already send some content as default?

    Also the event.dataTransfer.setData('text/html', null); method, curiously cannot send an empty string like event.dataTransfer.setData('text/html', ''); otherwise the dragover event will not be dispatched.