0

I am using function that makes a clicked button bold while making its other sibling buttons normal font weight. The function works correctly but I am getting a warning in JSHint saying Functions declared within loops referencing an outer scoped variable may lead to confusing semantics. (gLength, buttonParent). I tried using let instead of var in the code below but the warning is still there. How can I fix the issue that JSHint shows?

function boldButton(buttonParent) {
  buttonParent = buttonParent.querySelectorAll("BUTTON");
  if (buttonParent) {

    for (var g = 0, gLength = buttonParent.length; g < gLength; g++) {
      // set all buttons as normal font before setting a clicked button as bold font:
      buttonParent[g].addEventListener('click', function() {
        for (var r = 0; r < gLength; r++) {
          buttonParent[r].style.fontWeight = "normal";
        }
        // set the clicked button as bold font:
        this.style.fontWeight = "bold";
      }, false);
    }
  }
}

var buttonWrap = document.getElementById("button-wrap");
boldButton(buttonWrap);
<div id="button-wrap">
  <button>Button 1</button>
  <button>Button 2</button>
  <button>Button 3</button>
</div>
JAT86
  • 997
  • 12
  • 24
  • 1
    Just use a named function declared outside of the loop, then reference it by name inside the loop. – Bergi Sep 12 '21 at 17:05
  • 1
    I don't know how sophisticated jshint is, but try using `const` for the variables it complains about (`gLength`, `buttonParent`) instead of `let` or `var`. Or ignore the warning :-) – Bergi Sep 12 '21 at 17:07
  • 1
    Your intuition with using `let` was a good start; this code can lead to the [closure inside loops problem](/q/750486/4642212). In this case, however: use [event delegation](//developer.mozilla.org/docs/Learn/JavaScript/Building_blocks/Events#Event_delegation) instead of assigning multiple event listeners — it’s more maintainable, and applies to dynamically added elements.See [the tag info](/tags/event-delegation/info) and [What is DOM Event delegation?](/q/1687296/4642212). E.g., use `addEventListener("click", ({ target }) => target.closest("#button-wrap")?.children?.forEach((btn) =>`…`));`. – Sebastian Simon Sep 12 '21 at 17:07
  • @SebastianSimon "*this code can lead to the closure inside loops problem*" - actually it doesn't, since the closed-over variables are immutable. – Bergi Sep 12 '21 at 17:08
  • @Bergi Sorry, I meant “code for which this warning is triggered, can …”. – Sebastian Simon Sep 12 '21 at 17:10

0 Answers0