0

I'm new to JavaScript and trying to figure out a lot of stuff and trying to improve in the grammar.

I've got the following .js code which was provided and i:

(function(document) {
  const buttons = document.querySelectorAll('[data-next]');

  for (const item of buttons) {

    const parentId = item.getAttribute('data-parent');

    const parent = document.querySelector(`#${parentId}`);

    const nextDivId = item.getAttribute('data-next');

    const nextDiv = document.querySelector(`#${nextDivId}`);

    if (!nextDiv) {
      console.error('could not find next div for button ', item);
    }

    item.addEventListener('click', function() {
      nextDiv.classList.toggle('hidden');
      parent.classList.toggle('hidden');
    });
  }
})(document);

The way I know how to write a function is

function nameFunction(nameVariable) {
   code here
}

So I'm not getting how the first (function(document) and last line work })(document);

Hope someone can educate me in this :) Many thanks!

number42
  • 107
  • 7

1 Answers1

1

What you are talking about is IIFE(Immediately Invoked Function Expression). You can check this link for details information. You can also check this stackoverflow-link

Sifat Haque
  • 5,357
  • 1
  • 16
  • 23