0

When I drag and drop the green box into another col I get this error:

this.append is not a function

Why?

https://jsfiddle.net/gdxwks0t/1/

const cols = document.getElementsByClassName('col')
const item = document.querySelector('.item')

for (const col of cols) {
  col.addEventListener("dragover", (e) => {
    e.preventDefault()
  })
  col.addEventListener("drop", () => {
    alert(this)
    this.append(item)
  })
}
<div class="col">
  <div draggable="true" class="item"></div>
</div>
<div class="col"></div>
<div class="col"></div>
Anonymous
  • 11,748
  • 6
  • 35
  • 57
baDrosa82
  • 117
  • 1
  • 2
  • 7
  • 1
    If you want `this` within the call to the handler to be set by the DOM, don't use an arrow function. Arrow functions *close over* `this`, they don't get it set by how they're called like traditional functions do. See the linked question for details. – T.J. Crowder Dec 21 '19 at 12:59
  • 1
    you can also use `event.target.append(item);` – Yousaf Dec 21 '19 at 13:06

1 Answers1

1

Arrow (=>) function expressions

An arrow function expression is a syntactically compact alternative to a regular function expression, although without its own bindings to the this, arguments, super, or new.target keywords.

Use normal function syntax instead.

const cols = document.getElementsByClassName('col')
const item = document.querySelector('.item')

for (const col of cols) {
  col.addEventListener("dragover", (e) => {
    e.preventDefault()
  })
  col.addEventListener("drop", function() {
    alert(this)
    this.append(item)
  })
}
body {
  background: #ccc;
}
.item {
  background: #6dc06d;
  width: 50px;
  height: 50px;
  margin: 10px;
}
.col {
  float: left;
  width: 70px;
  height: 70px;
  background: white;
  margin: 10px;
}
<div class="col">
  <div draggable="true" class="item"></div>
</div>
<div class="col"></div>
<div class="col"></div>
Mamun
  • 66,969
  • 9
  • 47
  • 59