Pushing events back to Liveview

I am learning to do drag and drop in Liveview. Using HTML Drag & Drop API, I am able to drag & drop elements but is there a way to raise an event back to Liveview to trigger more actions from the event handler?

`
function allowDrop(ev) {
ev.preventDefault();
}

  function drag(ev) {
    ev.dataTransfer.setData("text", ev.target.id);
  }

  function drop(ev) {
    ev.preventDefault();
    var data = ev.dataTransfer.getData("text");
    ev.target.appendChild(document.getElementById(data));        
  }
</script>`
1 Like

You can use hooks to link js with LV elements: JavaScript interoperability — Phoenix LiveView v0.17.9

2 Likes

Thank you helping. Please forgive me for asking a very newbie question. Is this how it is done?

let Hooks = {}
Hooks.ElementDrop = {

    mounted() {
        function allowDrop(ev) {
            ev.preventDefault();
        }

        function drag(ev) {
            ev.dataTransfer.setData("text", ev.target.id);
        }
 
        function drop(ev) {
            ev.preventDefault();
            var data = ev.dataTransfer.getData("text");
            ev.target.appendChild(document.getElementById(data));
        }
    }
}

let liveSocket = new LiveSocket("/live", Socket, {
    params: {
        _csrf_token: csrfToken,
        hooks: Hooks,
    }
})

and in Liveview, I do this.

<div phx-hook="ElementDrop">

But this resulted in

unknown hook for “ElementDrop”

I spent the whole day trying to find a step-by-step intro for beginners to no avail. Can you point me in the right direction to get over this hurdle? Thank you!

In your mounted all you are doing is defining some functions, which aren’t being used. So you’re essentially doing nothing in the hook.

Do you want to be attaching some event handlers instead, using this.el.addEventListener(...)?

1 Like

Here are a couple of articles for integrating drag and drop with Live View. They use the older LEEx template syntax but should otherwise work for you to learn from.

1 Like

Hey thank you all for your suggestions. I will give it a try to see if I can make it work.

also see GitHub - seb3s/kandesk: Simple Kanban application written in elixir using phoenix liveview - which has drag and drop…

2 Likes