3

I have this code so far. I can see dragenter and dragleave events, but when I drop the file, the browser(Chrome or Firefox) just opens the file (a picture) even though preventDefault() is called. Anyone see any mistakes? What should I change?

 <script type="text/javascript">
    $(function () {
        var $box = $("#ulbox");
        $box.bind("dragenter", dragEnter);

        $box.bind("dragleave", dragLeave);
        $box.bind("drop", drop);

        function dragEnter(evt) {
            evt.stopPropagation();
            evt.preventDefault();
            console.log("dragEnter...");
            $(evt.target).addClass('over');
            return false;
        }
        function dragLeave(evt) {
            evt.stopPropagation();
            evt.preventDefault();
            console.log("drag leave...");
            $(evt.target).removeClass('over');
            return false;
        }


        function drop(evt) {
            evt.stopPropagation();
            evt.preventDefault();
            $(evt.target).removeClass('over');

            var files = evt.originalEvent.dataTransfer.files;

            if (files.length > 0) {
                alert("dropped");
                if (window.FormData !== undefined) {
                    var data = new FormData();
                    for (i = 0; i < files.length; i++) {
                        data.append("file" + i, files[i]);
                    }

                    $.ajax({
                        type: "POST",
                        url: "/api/upload",
                        contentType: false,
                        processData: false,
                        data: data,
                        success: function (res) {
                        }
                    });
                } else {
                    alert("browser sucks!");
                }
            }
            return false;
        }
         });
    </script>
 }

 <div id="ulbox" style="border: 5px dashed black; width: 300px; height: 100px;">
 </div>

1 Answer 1

1

Remove $box.bind("dragleave", dragLeave);

Add this : $box.bind("dragover", dragLeave);

it works charms .

Sign up to request clarification or add additional context in comments.

1 Comment

Do you know maybe how to prevent that browser opens picture when I drop picture outside dashed div instead of inside?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.