1

I am learning JavaScript on Udemy and there is a task to write a code that displays content when a "view more" button is clicked.

I can't understand how this works in the display content code and how JavaScript understands what the variable t is. I found a solution in the QA section, but I am not sure how it works. Apparently, the for i++ loop code is necessary so that the code works for each button in a tab.

Questions:

  1. How does this work here and why is it necessary?
  2. How does JavaScript understand what t is?
let desctiptionTab = document.querySelectorAll('.description-btn');

for (let i = 0; i < desctiptionTab.length; i++) {
  desctiptionTab[i].addEventListener('click', function() {
    Modal(this);
  });
}

function Modal(t) {
  overlay.style.display = 'block';
  t.classList.add('more-splash');
  document.body.style.overflow = 'hidden';
};

ford04
  • 66,267
  • 20
  • 199
  • 171
DLaningham
  • 23
  • 6
  • 2
    Well, `this` in an event handler is the object on which the event was triggered: https://stackoverflow.com/q/17665489/476. – deceze Aug 25 '19 at 08:08

1 Answers1

0

In your code, you are trying to achieve something on the click event of an HTML element. This is why you are attaching a click event using addEventListener.

Now, functions in JS have a run-time scope normally (unless you use call, bind or apply More Info), meaning that this value can change according to the context when the function is called. In your case, the value of this is the clicked HTML element, which you are using to pass to your Modal(t) as parameter t.

document.getElementById('hello').addEventListener('click', function() {
  console.log(this);
});
<div id="hello">Hello</div>
Nidhin Joseph
  • 9,981
  • 4
  • 26
  • 48