1

The navigation works fine but the sidenav should close when a link is clicked. Because it is a onepage. How can I do that? Can someone help me please.

Code:

function openNav() {
  document.getElementById("mySidenav").style.width = "250px";
}

function closeNav() {
  document.getElementById("mySidenav").style.width = "0";
}
.sidenav {
  height: 100%;
  width: 0;
  position: fixed;
  z-index: 1;
  top: 0;
  right: 0;
  background-color: #111;
  overflow-x: hidden;
  transition: 0.5s;
  padding-top: 60px;
}
<div id="mySidenav" class="sidenav">
  <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
  <a id="nav" href="#about">About</a>
  <a id="nav" href="#service">Services</a>
  <a id="nav" href="#contact">contact</a>

</div>
<p>Click to open</p>
<span style="font-size:30px;cursor:pointer" onclick="openNav()">&#9776; open</span>

The sidenav should close when a link is clicked

andy
  • 13
  • 6

2 Answers2

1

Your code works perfectly. You only seem to have forgotten to add closenav() to the onlick events on the actual links.

function openNav() {
  document.getElementById("mySidenav").style.width = "250px";
}

function closeNav() {
  document.getElementById("mySidenav").style.width = "0";
}
.sidenav {
  height: 100%;
  width: 0;
  position: fixed;
  z-index: 1;
  top: 0;
  right: 0;
  background-color: #111;
  overflow-x: hidden;
  transition: 0.5s;
  padding-top: 60px;
}
<div id="mySidenav" class="sidenav">
  <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
  <a id="nav" href="#about" onclick="closeNav()">About</a>
  <a id="nav" href="#service" onclick="closeNav()">Services</a>
  <a id="nav" href="#contact" onclick="closeNav()">contact</a>

</div>
<p>Click to open</p>
<span style="font-size:30px;cursor:pointer" onclick="openNav()">&#9776; open</span>
Nsevens
  • 2,588
  • 1
  • 17
  • 34
0

Try this one:

HTML:

<div id="mySidenav" class="sidenav jsSideNav">
          <a href="javascript:void(0)" class="">&times;</a>
          <a id="nav" href="#about">About</a>
          <a id="nav" href="#service">Services</a>
          <a id="nav" href="#contact">contact</a>
    </div>
    <p>Click to open</p>
    <span style="font-size:30px;cursor:pointer" class="jsToggleNav">&#9776; open</span>

CSS:

.sidenav {
  height: 100%;
  width: 0;
  position: fixed;
  z-index: 1;
  top: 0;
  right: 0;
  background-color: #111;
  overflow-x: hidden;
  transition: 0.5s;
  padding-top: 60px;
}
.sidenav.active {
    width: 250px;
}

JS:

$(document).ready(function(){
        $(".jsToggleNav").on('click', function(){
            if($(".jsSideNav").hasClass('active')) {
                $(".jsSideNav").removeClass('active');
            } else {
                $(".jsSideNav").addClass('active');
            }
        })
    });

I am assuming that you are using jquery, also follow the naming convention of class name that specifically used for js operations.

Hope this can help you.