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 div is lacking in height

I have 3 divs that belong to the stackContainer class: .stackContainer { position: relative; } Within these divs, I want multiple elements stacked on top of each other. To achieve this, I use the following code: .stackItem { position: absolute; ...

The image spills out of its confines

Looking to create a dialogue box that fills the entire width and height of the screen? Want to divide its content into two sections - an image and a footer area with 2 rows of height? Struggling to contain the image within its designated space without over ...

The specified number of columns and width values are being disregarded

The Challenge While using the CSS column-property to create columns on my webpage, I have encountered some unusual behavior with the layout engine. Specifically, I have set up the following styling: body { padding: 0; background-color: black; margi ...

Initiating an AJAX call to the Twitter API 1.1 search using jQuery

Check out this easy example of accessing Twitter's search API to retrieve tweets associated with a hashtag that is known for having a lot of activity, like #fml. I think I am using the application-only authentication properly according to this guide: ...

The marriage of Vue 2.0 and Rails 5: Shifting from Reactive to Declarative Rendering

As I make my way through the Vue guide with a Rails 5 app, I've noticed that although I am able to update my Vue js object, the DOM doesn't behave as described in the Declarative Rendering section. The data and the DOM are supposed to be linke ...

Customized figcaption formatting separate from the surrounding text

Is there a way to add a "figcaption" with independent settings to images placed alongside paragraphs in HTML? I have the following code snippet, but I'm unsure if I am using the figcaption tag correctly: <p><figure><span class="image ...

Is it possible to eliminate the css class prefix when using Modular css in React?

When working with React & NextJS, I have observed that my modular SCSS files are automatically prefixing my classnames with the name of the file. Is there a way to turn off this feature as it is making the DOM structure difficult to interpret? For instanc ...

AngularJs Datepicker malfunctioning after Data-dismiss operation

When using jquery datepicker in a AngularJs modal, it is important to initialize it correctly. Here is an example: <div class="col-md-2 rowdatepicker"> <label> RECORDING DATE </label> <input type="text" class="abs- ...

Automatically inserting a row into an HTML table

My table structure looks like this: <form name="frm_data_nasabah2" method="post" enctype="application/x-www-form-urlencoded" action="<?php echo $page_action;?>"> <table class="table table-bordered table-hover" id="tab_logic_ ...

Error message indicating that the jQuery script has not been properly defined in a Wordpress environment

Seeking assistance with a JavaScript issue on my WordPress site. I have added an external JS file but it's not functioning properly and throwing errors in the code below. Any help to resolve this would be greatly appreciated. var clock; jquery(docu ...

Is there a way to send HTML element values to a MySQL Database in Django using Ajax without utilizing a form?

As a Django newcomer, I am currently encountering an issue with posting HTML tag data into the database. I have implemented a "PICK CASE" button that, when clicked, should pass the user_id (hidden in an HTML tag with display:none) and case_id from the tag ...

implement adding a division element to the DOM using the append

I am facing an issue with this particular code. The intended functionality is to create multiple divs in a loop, but it seems to be dysfunctional at the moment. Upon clicking, only one div appears and subsequent clicks don't trigger any response. < ...

Rotate a shape to form a Rhombus at the center

I used the transform CSS property to create a rhombus, but I noticed that the center point of the shape is off-center to the right rather than in the middle. Can anyone help me figure out how to fix this issue? You can view my code here. .rhombus{ width ...

When using jQuery each method, it may return an [object Object]

Having an issue with the html variable displaying [object Object] instead of actual elements. Any suggestions on what I should change? var html = ''; $.each(data.response, function(index, value) { var tr = $('<tr>'); var ...

Glitchy/Crazy CSS3 Animations

Currently, I am developing a website at . One of the features I have implemented is CSS3 transitions for route changes, but this feature only works in Chrome. Here's how the animation works: I apply the .preanimate class to rotate the phasing out di ...

The textboxes are not displaying the floating numbers correctly

My issue involves 3 textareas with numbers displayed next to them. While I previously used a CSS table layout, it became inefficient when adding content between each row. I am puzzled as to why the second number, "2)", appears positioned next to the first ...

Is it possible to restrict the application of jquery .css() to a particular media query only?

Whenever a user's browser width is below 1160px, a media query is set up to hide my website's right sidebar. They can bring it back by clicking on an arrow icon, causing it to overlap the content with absolute positioning. To achieve this functi ...

Issues with FullCalendar functionality in CakePHP 1.2.5 are arising when using jQuery version 1.4.1

Currently, I am encountering an issue with fetching events data through a URL that returns JSON data. Surprisingly, the code works flawlessly with jQuery 1.3.2, however, it throws errors when using jQuery 1.4.1. The specific error message displayed in the ...

The class 'HttpServerUtility' does not include a function called 'encodeStringJavaScript'

I am currently attempting to refresh a Html.Action using JQuery in my perspective. My approach is based on the solution provided in this Stack Overflow post: How can I code a refresh of a HTML.RenderPartial using Ajax in MVC3? However, upon running the c ...

Refreshing all parts of a webpage except for a single div

Currently, I am in the process of creating a simple web page that includes a small music player (niftyPlayer). The individuals I am developing this for request that the player be located in the footer and continue playing when users navigate to different s ...