Hey campers,
Help would be really appreciated, I’ve been trying to figure this out for hours now.
So this was the solution to an exercise I was doing:
1. <!doctype html>
2. <tab-panel>
3. <div data-tabname="one">Tab one</div>
4. <div data-tabname="two">Tab two</div>
5. <div data-tabname="three">Tab three</div>
6. </tab-panel>
7. <script>
8. function asTabs(node) {
9. let tabs = Array.from(node.children).map(node => {
10. let button = document.createElement("button");
11. button.textContent = node.getAttribute("data-tabname");
12. let tab = {node, button};
13. button.addEventListener("click", () => selectTab(tab));
14. return tab;
15. });
16. let tabList = document.createElement("div");
17. for (let {button} of tabs) tabList.appendChild(button);
18. node.insertBefore(tabList, node.firstChild);
19. function selectTab(selectedTab) {
20. for (let tab of tabs) {
21. let selected = tab == selectedTab;
22. console.log(selected)
23. tab.node.style.display = selected ? "" : "none";
24. tab.button.style.color = selected ? "red" : "";
25. }
26. }
27. selectTab(tabs[0]);
28. }
29. asTabs(document.querySelector("tab-panel"));
30. </script>
the part that confused me is on line 13:
13. button.addEventListener("click", () => selectTab(tab));
Normally when adding event listeners, you wouldnt need to place a function call inside another function - it would be sufficient to say something like this:
button.addEventListener("click", selectTab(tab));
however when I do, an error comes up saying:
ReferenceError: tabs is not defined (line 15 in function selectTab)
called from line 7 in function Array.from.map.node
called from line 3 in function asTabs
called from line 25
and that’s where I’m lost.
Thanks for your time as always