-1

I am Beginner and making sidebar, I used JsHint to check js code error following error is showing but the sidebar is working please guide to fix error

This was the error

Two unused variables
1   openFunction
5   closeFunction

And here is my code

<div class="hamburger">
 <a href="javascript:void(0)"><i id="bars" onclick="openFunction();" class="fas fa-bars"
                    aria-hidden="true"></i></a>
   </div>
<!---------------------Sidebar--------------------------->
<div id="bg-sidenav" onclick="closeFunction();"  class="bg-sidebar">
</div>
<div id="sidebar-cont" class="sidebar-content">
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</div>

And here is Javascript Code

    function openFunction(){
      document.getElementById('sidebar-cont').style.width = "220px";
      document.getElementById('bg-sidenav').style.width = "100%";
  }
  function closeFunction() {
      document.getElementById('sidebar-cont').style.width = "0";
      document.getElementById('bg-sidenav').style.width = "0";
  }
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
  • 'please guide to fix error': What error? Please add some more details. – 0stone0 Oct 22 '21 at 11:25
  • 2
    Well, obviously JSHint cannot see your usages of the two functions in your HTML. These are linter warnings, not errors. Inline event handlers like `onclick` are [not recommended](/q/11737873/4642212). They are an [obsolete, hard-to-maintain and unintuitive](/a/43459991/4642212) way of registering events. Always [use `addEventListener`](//developer.mozilla.org/docs/Learn/JavaScript/Building_blocks/Events#inline_event_handlers_%E2%80%94_dont_use_these) instead. jQuery’s [`.on`](//api.jquery.com/on/) can also be used. – Sebastian Simon Oct 22 '21 at 11:25

1 Answers1

0

As @Sebastian Simon said in his comment, use addEventListener to attach your handlers:

<div class="hamburger">
 <a href="javascript:void(0)"><i id="bars" class="fas fa-bars"
                    aria-hidden="true"></i></a>
   </div>
<!---------------------Sidebar--------------------------->
<div id="bg-sidenav" class="bg-sidebar">
</div>
<div id="sidebar-cont" class="sidebar-content">
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</div>

And find the elements in the DOM and then attach the handlers using JavaScript:

function openFunction(){
  document.getElementById('sidebar-cont').style.width = "220px";
  document.getElementById('bg-sidenav').style.width = "100%";
}

function closeFunction() {
  document.getElementById('sidebar-cont').style.width = "0";
  document.getElementById('bg-sidenav').style.width = "0";
}

document.addEventListener("DOMContentLoaded", () => {
  const barsElement = document.getElementById('bars');
  const sidenavElement = document.getElementById('bg-sidenav');

  bars.addEventListener('click', openFunction);
  sidenavElement.addEventListener('click', closeFunction);
});
Tom
  • 1,158
  • 6
  • 19