0

Why are console.log(this) = window instead of the "wrapper"-div? I use a arrow function because that would bind this to the div?

const slider = document.querySelector(".wrapper");
let isDown = false;

slider.addEventListener('mousedown', () => {
  console.log(this);
  isDown = true;
  slider.classList.add('active');
});

<!DOCTYPE html>
<html lang="sv">
  <head>
    <title>Drag and drop</title>
    <meta charset="utf-8">
    <link rel="stylesheet" href="main.css">
  </head>
  <body>
   <div class="wrapper">
     <div class="item item1">1</div>
     <div class="item item2">2</div>
     <div class="item item3">3</div>
     <div class="item item4">4</div>
     <div class="item item5">5</div>
   </div>
    <script src="main.js"></script>
  </body>
</html>
Adam
  • 69
  • 1
  • 11
  • 2
    *"I use a arrow function because that would bind this to the div?"* It's exactly the opposite. Related: [Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?](http://stackoverflow.com/q/34361379/218196) – Felix Kling Jan 18 '17 at 14:07

1 Answers1

4

I use a arrow function because that would bind this to the div?

No, arrow functions close over the this where they're defined, and this isn't the div where you're creating that arrow function. Moreover, arrow functions don't have a this of their own (because they close over it), so the event mechanism can't call it with the correct this as it normally would.

Use a normal function instead, or use slider instead of this.

Using a normal function:

slider.addEventListener('mousedown', function() { // ***
  console.log(this);
  isDown = true;
  this.classList.add('active');
});

Using slider (just for completeness; you already were):

slider.addEventListener('mousedown', () => {
  isDown = true;
  slider.classList.add('active');
});
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875