Why is preventDefault not working?

This is part of my code. If I try to reset the image on the preventDefault block it doesn't work.

        jQuery(document).ready(function($) {
            $.event.props.push('dataTransfer');
            $('#imgDropzone').on({
                dragenter: function(e) {
                    $(this).css('background-color', '#ffd1ff');
                },
                dragleave: function(e) {
                    $(this).css('background-color', '');
                },
                drop: function(e) {
                    e.stopPropagation();
                    e.preventDefault();

                    var file = e.dataTransfer.files[0];
                    var fileReader = new FileReader();
                    var el = $(this);
                    fileReader.onload = (function(file) {
                        return function(event) {
                            alert(event.target.result);
                        };
                    })(file);
                    fileReader.readAsDataURL(file);
                }
            });
        });

      

http://jsfiddle.net/LrmDw/

+3


source to share


1 answer


You need * to prevent all other drag and drop events by default:

see http://jsfiddle.net/LrmDw/2/

$('#imgDropzone').on("dragenter dragstart dragend dragleave dragover drag drop", function (e) {
    e.preventDefault();
});

      

To explain what's not working in the original jsfiddle:

When you drop a file into droparea (or anywhere on the page), the browser's default behavior is to navigate and try to interpret the file. If you drop the normal txt, for example, the browser will navigate away from the jsfiddle and display the contents of the txt file. It's in Chrome.




Btw, base64 urls are not preferred as they duplicate data. Just grab the blob pointer to the file and use this:

var file = e.dataTransfer.files[0];
var src = (window.URL || window.webkitURL).createObjectURL(file);
$("<img>", {src: src}).appendTo("body");

      

Cm

http://jsfiddle.net/LrmDw/3/

I don't know which ones, but I never had to care

+14


source







All Articles