Basic selection menu layout

I have put together a basic menu for my WordPress site without relying on classes or IDs:

<div class="main-menu">
  <nav>
    <ul>
      <li>
        <a href="#" class="menu-link">home</a>
      </li>

      <li>
        <a href="#" class="menu-link">product</a>
        <ul>
          <li>
            <a href="#">XXXX</a>
          </li>

          <li>
            <a href="#">XXXX</a>
          </li>

          <li>
            <a href="#">ZZZZ</a>
            <ul>
              <li>
                <a href="#">XXXX</a>
              </li>

              <li>
                <a href="#">XXXX</a>
              </li>

              <li>
                <a href="#">XXXX</a>
              </li>
            </ul>
          </li>
        </ul>
      </li>

      <li>
        <a href="#" class="menu-link">more</a>
      </li>
    </ul>
  </nav>
</div>

I then used this CSS to hide the sub-menu:

.main-menu ul li ul {
    display: none;
}

Previously, I had a script that showed the mini menu when the menu was clicked:

$('.menu').click(function(evt) {
    evt.preventDefault();
    $(".mini_menu").show();
});

Now, I am in need of a new script that will show the sub-menu when any of the li's is clicked.

Answer №1

To display your menu when a list item is clicked, use the $(this) method along with children('ul'), avoiding the need for classes.

For example:

$('.main-menu').find('li').click(function(e) {
  e.stopPropagation();
  $(this).children('ul').toggle();

});
.main-menu ul li ul {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main-menu">
  <nav>
    <ul>
      <li>
        <a href="#" class="menu-link">home</a>
      </li>

      <li>
        <a href="#" class="menu-link">product</a>
        <ul>
          <li>
            <a href="#">XXXX</a>
          </li>

          <li>
            <a href="#">XXXX</a>
          </li>

          <li>
            <a href="#">ZZZZ</a>
            <ul>
              <li>
                <a href="#">XXXX</a>
              </li>

              <li>
                <a href="#">XXXX</a>
              </li>

              <li>
                <a href="#">XXXX</a>
              </li>
            </ul>
          </li>
        </ul>
      </li>

      <li>
        <a href="#" class="menu-link">more</a>
      </li>
    </ul>
  </nav>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Keystrokes may not consistently register in Firefox

I created a compact web application where users can interact by clicking on a button to trigger a modal dialog. Within this dialog, users have the ability to choose from various options. To enhance user experience, I implemented the utilization of the jQue ...

The width:auto attribute for images in ie6 is not functioning as expected

I am facing a challenge with dynamically changing and resizing an image element to fit its container. My current approach involves: Resetting the image: // Ensuring the 'load' event is re-triggered img.src = ""; // Resetting dimensions img. ...

Error: The JSON in app.js is invalid due to the unexpected token "C" at position 0

When I try to run this code snippet, I sometimes encounter an error message that says: SyntaxError: Unexpected token C in JSON at position 0. function fetchData(user_country) { fetch(`https://covid19-monitor-pro.p.rapidapi.com/coronavirus/cases_by_day ...

"An in-depth guide on parsing JSON and showcasing it in an HTML format

As part of my order processing, I am saving the order details into a JSON file named order_details.json. Here is an example of how the data is structured: [{ "uniqueID": "CHECKOUT_IE01", "orderID": "4001820182", "date": "06-02-2019 16:55:32.32 ...

What is the reason that in jsxgraph, a parabola is not able to be created by connecting five points on a single plane?

I recently encountered an issue while working on a project involving drawing points in 3D space that move according to slider values. Even though the points moved correctly, I faced difficulty in drawing a conic section (specifically a parabola) through th ...

Error: Attempting to access the properties `line_items.amount`, `line_items.currency`, `line_items.name`, `line_items.description`, or `line_items` is not allowed

Hi there, I'm currently working on creating an Amazon-inspired platform and I've encountered an error while trying to integrate Stripe with the project. Can anyone provide some assistance? You can refer to the video tutorial I'm using by fol ...

Seeking assistance with jQuery getJSON - encountering issues with URL, requesting help

I've recently started learning jQuery and I've run into an issue with the getJSON function. Whenever I try to use it with a URL, I encounter an error, while it works perfectly fine when I use it with a text file. Can anyone help me figure out wha ...

An unexpected error occurred in NodeJS: It is not possible to adjust headers once they have been sent

Recently, I've been working on a nodejs project and encountered the error message "Can't set headers after they are sent" when trying to get a response from http://localhost:8080/api/user. Despite researching solutions on Stack Overflow, none of ...

Tips on adjusting the default width of the React player interface

I'm currently utilizing react-player to display a video in my app. The default width it comes with is not responsive, and applying CSS didn't prove to be effective. import ReactPlayer from 'react-player'; <ReactPlayer url="https:// ...

Is there a way to stop the execution of myFunc after it has been performed 5 times using clearInterval?

This code is designed to notify online shoppers that they need to choose a color from a dropdown menu before adding an item to their shopping cart. If no color is selected, the text will blink to alert them. How can I modify this code so that the blinking ...

Challenges arising from utilizing distinct list style types for both parent and child elements with the assistance of CSS List

I am experimenting with the CSS counter reset feature to create a numbering system on my website. The main list should be in regular decimal format (e.g. 1, 2, 3, 4) while the sub-list should be in upper Roman numerals (e.g. I, II, III, IV, etc). Below is ...

When accessing the defaultValue property of a select element, it will result in

Here is a typical HTML dropdown menu: <select name="email" id="email"> <option value="2" selected="selected">Before redirecting to PayPal</option> <option value="1">After payment is successful</option> <opti ...

Access the OpenWeatherMap API to retrieve the weather forecast for a single time slot within a 5-day period

Utilizing the openweathermap api, I am retrieving a 5-day/3-hour forecast here. The API call provides multiple results for each day with data available every 3 hours. For the full JSON response, you can access it here. Please note that the API key is only ...

What is the approach to initiating a jquery function once HTML content is dynamically added through an AJAX call?

<div id="timeline"> <ul class="grow" id="grown"><li>One</li><li>Two</li><li>Three</li><li>Four</li><li>Five</li><li>Six</li><li>Seven</li><li>Eight< ...

The Intriguing Riddle of HTML Semantic

I've been working on a puzzle presented in the link provided below: HTML Structure Challenge This mind-teaser consists of three questions: Modify the HTML code of the website to enhance its structure as follows: Replace the generic outer div eleme ...

The Laravel 5.4 Resource is encountering an Error 405, indicating that the PUT Method is not allowed when using

In my routes.php file: Route::resource('/users','UserController'); For ajax requests in ajax.js file: $.ajax({ url: "/users", type:'POST', data:$('.edit-user-for ...

substitute the character ""<0x00>"" within the given string

I'm currently facing an issue with a string I received after sending a command line that included the <0x00> character. How can I remove it from the string? For instance, here is my variable string: <0x00> awplus # desired output: awplus ...

Guide on how to initialize a variable in Express.js within a conditional statement in Node.js

Trying to create a variable based on a conditional statement, but even with simple code I am unable to retrieve the new variable. Here is my code: exports.productPatch = (req, res, next) => { const id = req.params.productId; const image = req.body.p ...

When integrating react-router 5 and redux 7, there is an issue where the state is not being reset when navigating to a new route using react-router's <Link

My current setup includes the following versions: `"react-router": "^5.2.0",` `"react-router-domreact-router": "^5.2.0",` I'm unsure if my setup is compatible with React-router 5 as I was using a version prior ...

The Page is Not Able to Scroll

Occasionally, my app stops allowing scrolling of the entire page length. Everything will be working fine for a while, but then out of nowhere, the page suddenly becomes un-scrollable and you can only interact with the section currently visible on the scree ...