I'm trying to add slots I can drag objects into on button click. but run into the error
Uncaught TypeError: Cannot read property 'dataTransfer' of undefined...
The html is in the <body>
and the javascript is in the <head>
if that matters.
This is my Javascript:
<script>
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.originalEvent.dataTransfer.setData("text", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var data = ev.originalEvent.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
function addRow() {
const div = document.createElement('div');
div.className = 'dragcontainer';
div.draggable = true;
div.ondrop = drop(event);
div.innerHTML = ``;
div.ondragover= allowDrop(event);
document.getElementById('content').appendChild(div);
}
</script>
And here is the html:
<input type="button" value="add slot" onclick="addRow()">
<div id="content">
<div id="div1" class="dragcontainer" ondrop="drop(event)" ondragover="allowDrop(event)">
<ul draggable="true" ondragstart="drag(event)" id="drag1">
<li><h1>Sample title</h1></li>
<li><p>sample text</p></ul></li>
</div>
<div id="div2" class="dragcontainer" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
</div>
You are calling functions instead of setting them as values. Look at the comments I've added
function addRow() {
const div = document.createElement('div');
div.className = 'dragcontainer';
div.draggable = true;
// You are calling drop(event)
// Change to div.ondrop = drop;
div.ondrop = drop(event);
div.innerHTML = ``;
// You are calling allowDrop(event)
// Change to div.ondragover = allowDrop;
div.ondragover= allowDrop(event);
document.getElementById('content').appendChild(div);
}