Toggle display of list items using jQuery on click event

I want to be able to toggle the visibility of my submenus when a link is clicked. Here's an example code snippet:

<ul>
        <li><a href="www.example.com">Test</a></li>
        <li><a href="www.example.com">Test</a></li>
        <li class="submenu">
            <a href="#">Test 2</a>
            <ul class="ul_submenu">
                <li><a href="www.example.com">Test</a></li>
                <li><a href="www.example.com">Test</a></li>
                <li class="submenu_2">
                    <a href="#">Test 3</a>
                    <ul class="ul_submenu_2">
                        <li><a href="www.example.com">Test</a></li>
                    </ul>
                </li>
            </ul>
        </li>
    </ul>
$( 'li.submenu a[href="#"]').click(function(e) {
        e.preventDefault();
        $("ul.ul_submenu").toggle();
    });
    

You can view a working example on JSFiddle.

I need the ability to click on a link even if it has child elements, and change the display of the list item. However, I also want to prevent the page from reloading when a link like this is clicked: <a href="#"></a>

Answer №1

Here is a simple jQuery code snippet that allows you to toggle a submenu when clicking on a list item:

$('li a').click(function(e) {
  e.preventDefault();
  $(this).closest("li").find("[class^='ul_submenu']").slideToggle();
});

Check out this Fiddle for demonstration.

Answer №2

Simply include a false return statement in the click callback function. The click() method should have only one callback function, not two. What was your initial plan?

Also, you can avoid using css() and instead utilize show().

$(function() {
    $('li.submenu a[href="#"]').click(function(e) {
        e.preventDefault();
        $("ul.ul_submenu").show()
        return false;
    });
});

To make it more dynamic, you could consider structuring it similar to this example for all menu entries. I've made some adjustments to your fiddle: https://jsfiddle.net/sy757gvj/5/

<ul>
  <li><a href="www.example.com">Test</a></li>
  <li><a href="www.example.com">Test</a></li>
  <li class="submenu"><a href="#">Test 2</a>
    <ul class="ul_submenu">
      <li><a href="www.example.com">Test</a></li>
      <li><a href="www.example.com">Test</a></li>
      <li class="submenu"><a href="#">Test 3</a>
        <ul class="ul_submenu">
          <li><a href="www.example.com">Test</a></li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

-

$(function() {
    $('li.submenu a[href="#"]').click(function(e) {
        e.preventDefault();
        $(this).next().toggle();
        return false;
    });
});

Answer №3

To activate the "Test2" submenu, you can use the following code:

$('li.submenu a[href="#"]').click(function(e) {
   e.preventDefault();
   $(this).parent().children("ul.ul_submenu").show();
});
.ul_submenu {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li><a href="www.example.com">Test</a></li>
  <li><a href="www.example.com">Test</a></li>
  <li class="submenu"><a href="#">Test 2</a>
    <ul class="ul_submenu">
      <li><a href="www.example.com">Test</a></li>
      <li><a href="www.example.com">Test</a></li>
      <li class="submenu_2"><a href="#">Test 3</a>
        <ul class="ul_submenu_2">
          <li><a href="www.example.com">Test</a></li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

Answer №4

One way to achieve this is by utilizing the toggle function.

$(document).ready(function(){
    $('li.submenu a[href="#"]').click(function(){
        $("ul.ul_submenu").toggle();
    });
});

Answer №5

I updated the jquery code as follows:

$('li.submenu').on('click','a[href="#"]',function(e){
    e.preventDefault();
    $("ul.ul_submenu").toggle();
})

It appears to be working fine now. Check it out on this Fiddle: https://jsfiddle.net/y0p13dt7/1/

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

The marquee HTML code is not functioning correctly in the Chrome browser

<marquee behavior="scroll" scrollamount="2" direction="right" width="70%" style="background-color: transparent; height: 18px;" onmouseover="this.stop();" onmouseout="this.start();"> 1 2 3 4 5 6 7 //inside html </marquee> Th ...

Having difficulty submitting a form with ajax, while accomplishing the same task effortlessly without ajax

I have been experimenting with submitting a form using ajax to the same .php file. When I submit the form without ajax directly (form action), the database gets updated. However, when I try the same process with ajax, there is no change in the database. H ...

When using jQuery to add an item to a List, it disappears immediately after

I am facing an issue with the code I have. Whenever I click on the "Add" button to add an item, it briefly appears in the list but then disappears. I'm having trouble figuring out why this is happening. $(document).ready(function() { $("#submitB ...

I attempted various methods but was unable to successfully call the webmethod in the code behind using jQuery Ajax and Knockout

I have attempted various solutions, such as enabling friendly URL resolution and utilizing web method with session enabled, but unfortunately, the issue remains unresolved. I kindly request your assistance in resolving this matter. Here is my HTML code for ...

The input field in Angular dynamically populates values into multiple instances of the same text

I am facing an issue with my comment inputs where whatever I type in one input is automatically populated in all other inputs. How can I ensure that the text input value only appears in the input box that I am typing into? Below is a snippet of the templa ...

JavaScript stylesheet library

What is the top choice for an open-source JavaScript CSS framework to use? ...

Slideshow featuring cards with text overlay

I am working with a bootstrap carousel and trying to place a card with text on top of it. No matter what I try, the card is not appearing as desired. Here is an example of what I want to achieve: https://i.sstatic.net/tjW3w.png Below is the code snippet: ...

Conceal the child elements underneath a selected element using jQuery

I am currently working on an order form within a website and the HTML code is structured as below: <table class="variations"> <div class="tawcvs-swatches" data-attribute_name="attribute_pa_t-shirt- one-color"> <span class="swat ...

Adapting CSS according to input selection

Forgive me for asking what may seem like a simple question. I am currently using the CSS code below to modify the background color of a label when its associated checkbox is checked: #project input[id="button1"]:checked + label {background-color:red;} Is ...

Add a sound file to the server and configure the images based on the server's response

I am a newcomer to JavaScript and AJAX, and I am facing an issue while trying to upload an audio file to the server and display the image from the server response. When attempting to pass the audio file from the input tag to an AJAX call, I encounter an il ...

Are we utilizing this JavaScript function properly for recycling it?

Two functions have been implemented successfully. One function adds the autoplay attribute to a video DOM element if the user is at a specific section on the page. The other function smoothly slides in elements with a transition effect. The only limitatio ...

Is there a way to refresh a specific element without having to reload the entire page when the button is clicked

While working on a rock, paper, scissors game in JavaScript, I found it tedious to have to constantly reload the page after each play. To solve this issue, I attempted to add a button that would reset the game for a new round. However, I encountered an err ...

consistent height across the div when expanding

There is a recurring issue I encounter where it takes too long for me to solve the problem. My goal is to ensure that the bootstrap boxes at the bottom of the page have the same height. I attempted to set a fixed height in pixels using my CSS, but this cau ...

How can I make multiple elements in the same column span across multiple rows with CSS Grid?

Here is a scenario where the HTML and CSS (specifically the .type-a section) utilize CSS Grid. (Click here to view the CodePen example) The goal is to ensure that all elements with the .col1 class are aligned correctly in the first column, while having t ...

Using a forward slash in the path for the href attribute in a CSS link within an ejs file

Image 1: Configuring express.static for the public folder Image 2: Adding href="/app.css" in post.ejs file Image 3: Final result While experimenting with using /app.css and app.css in the post.ejs file, I noticed that the outcome was consistent with th ...

Using jQuery to Send a POST Request and Delete a File when a Button is

Seeking assistance for a project I'm working on. I have created this page where users can access an image gallery. Currently, I am adding a feature to allow users to delete images. Following advice from the community here here, I am exploring the jQ ...

Achieving a full-screen div or video that remains fixed in a specific position on the browser window can be done by following these steps

I am seeking guidance on how to create a video or div that remains fixed in a specific position while adjusting its size to always match the browser window. You can see an example of what I am aiming for here. The website mentioned above contains a video ...

How can I create a redirect link in HTML that opens in a new window

I have a HTML page where I need to redirect to the next page. <a href="www.facebook.com" target="_blank">www.facebbok.com</a> Currently, it is redirecting to localhost:9000/dashboard/www.facebook.com But I only want to redirect to www.facebo ...

How can I ensure that a div is positioned over another div with the same coordinates across all screen sizes?

[http://jsfiddle.net/w7r3gveg/]1 I am looking to position 4 Facebook logos in the center bottom of my background image. The background is represented by the 'bg' div, while the Facebook logo is in the 'facebook' div. Currently, I can ...

Showing nested arrays in API data using Angular

I would like to display the data from this API { "results": [ { "name": "Luke Skywalker", "height": "172", "mass": "77", & ...