-4

I'm a beginner in javascript. I want to add hide and show button using toggle methods. Here is my html.

<body>
  <header>
    <li><a href="#">Mécanique</a>
      <ul class="sub-menu">
        <li><a href="#">Mécanique du point</a></li>
        <li><a href="#">Mécanique du solide</a></li>
      </ul>
    </li>

  </header>
</body>
Rachel Gallen
  • 27,943
  • 21
  • 72
  • 81
moradov
  • 109
  • 3

1 Answers1

0

Learn how things work before you ask a question here at StackOverflow. We all still learning, but, we have to try things ourselves.

Besides that, here's how to use jQuery to hide/show .sub-menu by clicking the a tag that contains 'Mécanique' word, and I'll give it an ID so we can reference it later by JavaScript.

// we put everything in the document.ready handler to ensure that the document has finished loading.
$(document).ready(function() {
  // reference the 'a' tag that I gave it an id of 'trigger', and also referencing the .sub-menu ul.
  var trigger = $('#trigger'),
    menu = $('.sub-menu');
  // adding the event listener to the #trigger to hide/show the .sub-menu ul.
  trigger.on('click', function(e) {
    // cancel the default behaviour when clicking a link.
    e.preventDefault();
    // hide/show the menu.
    menu.toggle();
  });  
});
ul.sub-menu {
  // by default, let's make the .sub-menu ul hidden.
  display: none;
}
    <body>
      <header>
        <li><a href="#" id="trigger">Mécanique</a>
          <ul class="sub-menu">
            <li><a href="#">Mécanique du point</a></li>
            <li><a href="#">Mécanique du solide</a></li>
          </ul>
        </li>

      </header>
      <script
  src="https://code.jquery.com/jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous"></script>
    </body>

Hope I pushed you further.

ThS
  • 4,597
  • 2
  • 15
  • 27