Home > other >  Drag and Drop: Drop in non-valid dropzones
Drag and Drop: Drop in non-valid dropzones

Time:07-14

I’m working on a drag and drop web application using Vue.JS and Vuex Store. The functionality is implemented pretty much following the mdn docs for “HTML Drag and Drop API”. So my Dropzone Component and Draggable Element Components work with event.preventDefault(). As I have nested Dropzones, I also use event.stopPropagation() on the Dropzones. Drag and drop with the designated compoents works fine.

Nested dropzones illustration

My problem is: When a user drops a Draggable Element outside of a Dropzone, the UI kind of breaks. So what I’m looking for is a app-wide event Listener for drops in non-valid dropzone areas.

I tried it with a global “dragend” listener, but that doesn’t seem to work. I also tried “mouseup”, but that seems to general. Here’s what I tried:

new Vue({
    router,
    store,
    render: (h) => h(App),
    async created() {
        window.document.addEventListener('dragend', (e) => {
            console.log("global Dragend -------------- ");
        })

        window.document.addEventListener('mouseup', (e) => {
            console.log("global Mouseup -------------- ");
        })
    },
}).$mount('#app');

I'm hoping that somebody knows how to implement an app-wide EventListener that triggers after failed drops.

CodePudding user response:

You could add a 'no-drop' class to the elements that you don't want to be drop zones. And then when drop event received you can prevent drop

How to prevent drop into a div element?

CodePudding user response:

Solution

I found a solution which was quite simple in the end. I set up "ondrop" and "ondragover" Events on my main Vue component. If a user drops a draggable element outside of a valid dropzone, the "ondrop" Event fires and I can handle my UI errors there.

    <template>
      <div
          @drop="wrongDrop"
          @dragover="wrongDragOver"
      >
      <!--Code-->
      </div>
    </template>
    
    
    <script>
    methods: {
        wrongDrop(event) {
          event.preventDefault();
          // drop outside of a valid dropzone
          // do things to handle errors
        },
        wrongDragOver(event) {
          event.preventDefault();
        },
    }
    </script>
  • Related