-1

So I'm dealing with a little problem..

I'm trying to modify drag-and-drop code and came across a problem, since I want to have multiple drop areas and one function for all of them.

I have this code:

dropArea.addEventListener("dragover", (event)=>{
  event.preventDefault(); //preventing from default behaviour
  dropArea.classList.add("activated");
  dragText.textContent = " Release to Upload File";
});

And specified dropareawitth querySelector:

const dropArea = document.querySelector(".drag-area")

Now I need to modify it to work with multiple drop zones. I thought to just replace the "droparea" inside the event to "this" something like that:

this.classList.add("activated");

but it does not work. I even tried:

$(this).classList.add("activated");

Returns this error:

Uncaught TypeError: Cannot read properties of undefined (reading 'add')

Any solutions? I'm stuck...

David Stančík
  • 340
  • 6
  • 23

1 Answers1

1

As your event handler is an arrow function, the value of this is not influenced by the caller, so you cannot use it to get the DOM element. You can use event.target.

event.target.classList.add("activated");

As to your final attempt: $() does not return a DOM element, but an array-like "jQuery" collection object, which doesn't have such properties as classList.

trincot
  • 317,000
  • 35
  • 244
  • 286
  • what does ```this``` represent in an arrow function? – seriously Jan 16 '22 at 11:33
  • 2
    For arrow functions, `this` is determined by the function execution context *around* it. If this is a top-level context, then `this` will be `undefined` or the global object. But it is not influenced by the actual call. It just has the same `this` as the immediately surrounding code would have. – trincot Jan 16 '22 at 11:34
  • @seriously See [Arrow function expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) – Ouroborus Jan 16 '22 at 11:36