Edward Coom
Edward Coom

Reputation: 37

Menu is initially open on page load, should be closed until clicked

This may be a silly question but I cannot figure out why my menu displays when the page is loaded. I would like to have it closed and then opened when it is clicked but it is the other way around and I can't seem to fix it.

<html>
<head>
<script>
    $(document).ready(function () {
    $('#nav p')
        .css({ cursor: "pointer" })
        .on('click', function () {
            var txt = $(this).text() == "MENU" ? "CLOSE" : "MENU";
            $(this).text(txt);
            $(this).next('ul').toggle();
        })
    });
</script>
</head>

<body>
    <div class="left" id="nav">
        <p>CLOSE</p>
        <ul>
            <li id="light">
                <a href="lighting_video.html">Lighting + Video</a>
            </li>
            <li id="photo">
                <a class="active" href="photograms.html">Photograms</a>
            </li>
            <li id="about">
                <a href="about.html">About</a>
            </li>
        </ul>
    </div>
</body>

</html>

Upvotes: 0

Views: 756

Answers (2)

Nimitt Shah
Nimitt Shah

Reputation: 4587

You can do most of the stuff from CSS. Create .closed class and assign it to #nav.

#nav.closed > ul{
  display: none;
}

That's it. You are done with minor changes in jQuery click event!

See the snippet below.

$(document).ready(function(){
  $('#nav p').on('click', function(){
      $(this).parent().toggleClass("closed");
    });
  });
#nav{
  cursor: pointer;
}
#nav.closed p::after{
  content : "CLOSE";
}
#nav p::after {
  content: "MENU";
}
#nav.closed > ul{
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="left closed" id="nav">
  <p></p>
  <ul>
    <li id="light">
      <a href="lighting_video.html">Lighting + Video</a>
    </li>
    <li id="photo">
      <a class="active"href="photograms.html">Photograms</a>
    </li>
    <li id="about">
      <a href="about.html">About</a>
    </li>
  </ul>
</div>
</body>
</html>

Upvotes: 0

Plum
Plum

Reputation: 71

$(document).ready(function(){
  $('#nav p')
    .css({cursor: "pointer"})
    .on('click', function(){
      var txt =  $(this).text() === "MENU"?"CLOSE":"MENU"; // 3 egals verification
      $(this).text(txt);
      $(this).next('ul').toggle();
  })
  });
ul{
  display: none; /* ADD this */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="left" id="nav">
  <p>CLOSE</p>
  <ul>
<li id="light">
<a href="lighting_video.html">Lighting + Video</a>
</li>
<li id="photo">
<a class="active"href="photograms.html">Photograms</a>
</li>
<li id="about">
<a href="about.html">About</a>
</li></ul>
</div>
</body>
</html>

Upvotes: 1

Related Questions