There seems to be an issue with the behavior of the click-to-toggle menu implemented with jQuery

I can't seem to figure out why my pop-up menu in jQuery is acting so strange and unpredictable.

The menu is supposed to appear on a toolbar located at the bottom of the window when clicked (not hovered). It should then disappear again when: a) a menu item is clicked, b) the toolbar button that opened it is clicked again, c) or when anything else on the page is clicked.

Initially, everything was working perfectly, but now it's falling apart. I've encountered a frustrating glitch...

Here is what's happening:

  1. I load the page
  2. I click the first menu button, and it pops up as expected.
  3. I click the second menu button, and it pops up while the first one that was open closes.
  4. Keeping the second menu open, I click the first one again. Oh no! The second menu remains open too! Now both are open simultaneously!?!
  5. When I click something else on the page to hide the menus, only the first one disappears. The second one stubbornly stays open. I have to click its menu button to make it go away.

Help, please!!! Here is the link to my jsFiddle:

http://jsfiddle.net/xn4TN/31/

And this is the JavaScript I'm using:

    var togglemenu = null;
    function fn_togglemenu(datatarget) {
        $('.bottom-menu-bg ul li ul[data-target="' + datatarget + '"]').slideToggle(function() {
            togglemenu = $(this).is(':visible') ? datatarget : null;
            $('.bottom-menu-bg ul li ul[data-target="' + datatarget + '"]').parent('li a').toggleClass('hover');
        });
    }
    $(document).ready(function() {
        $('.bottom-menu-bg ul li a').click(function(ev){
            ev.preventDefault();
            fn_togglemenu($(this).attr('data-target'));
        });
        $(document).click(function(ev){
            if(togglemenu != null) {
                fn_togglemenu(togglemenu);
            }
        });
    });

There is too much code to include inline realistically.

Answer №1

To improve menu functionality, make sure to explicitly hide other menus when toggling. Use the following code:

function toggleMenu(target) {
    // Hide other menus
    $('.menu ul li ul').hide();
    $('.menu ul li').removeClass('active');
    // Show target menu
    $('ul[data-target="' + target + '"]').slideToggle(function() {
        $('ul[data-target="' + target + '"]')
            .parent('li a').addClass('active');
    });
 }

$(document).ready(function() {
    $('.menu ul li a').click(function(event) {
        event.preventDefault();
        event.stopPropagation();
        toggleMenu($(this).attr('data-target'));
    });

    $(document).click(function(event) {
        // Explicitly hide menus
        $('.menu ul li ul').hide();
    });
});

Note: Ensure to stop event propagation on link click handlers. Here is your updated jsfiddle: http://jsfiddle.net/uniqueusername/abcdefg/

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

Achieving Perfect Alignment for Absolutely Positioned Divs in

I'm currently facing an issue where the image I'm trying to center horizontally also moves the parent div downward when I try to vertically center it using top-margin. This is not the desired outcome. If you'd like to see what I mean, I&apo ...

Display user input within a modal dialogue box

I have a subscription form that requires users to enter their name and email address. After clicking on "Compete Now," a pop-up appears asking for workshop information and postal code. The form is functioning correctly as intended. However, I want the em ...

When the page loads, a JavaScript function is triggered

My switchDiv function in Javascript is being unexpectedly called when the page loads. It goes through each case in the switch statement, except for the default case. Does anyone know how to solve this issue? $(document).ready(function() { $("#be-button" ...

Please proceed with submitting your choices in the order that you have selected

My goal is to submit options from a dropdown list in the order they are selected, rather than in the order they appear in the list. How can I achieve this? Here is the HTML code for the dropdown: < select style = "padding: 1em;" name = "skills" multi ...

Interactive tables created using Google Visualization

I have a Google visualization data table that works well, but I am facing an issue with the width of the table. When I click as shown in the image, I call the function drawTable(); and then I encounter this: As you can see, the table does not have a width ...

Unraveling JSON Data from a PHP Website with Jquery

I need to retrieve data from a database and store it in an array, similar to the example below var locations = [ ['Current', 18.53515053, 73.87944794, 2], ['VimanNagar', 18.5670762, 73.9084194, 1] ]; To begin with, I have created a ...

Invoke the wrapper function within the jQuery AJAX `complete` callback

I am currently trying to accomplish a task, but I keep receiving an error message stating that I cannot bind to undefined. I suspect this is happening because I am working within an anonymous function. My goal is to be able to access the method (getAndSayH ...

Encountered JSON array, unable to retrieve certain attributes in AngularJS

I have developed a web service that organizes my information into a list and then converts it to JSON format. Below is the JSON output: { GetEventLTResult: [ { eventID: 1, location: "Place A", type: "Communi ...

File bootstrap.min.css is currently experiencing compatibility issues

I am currently working on a website where I have two images that are displaying vertically. However, I would like these images to be displayed horizontally with animation. I attempted to use Bootstrap to achieve this horizontal layout, but when I include ...

Prevent the next ajax request from overwriting the parameter value set in the previous request

When my application makes multiple ajax requests, I encounter a problem where the original set of parameters used for each request get changed by subsequent requests, leading to errors. Let's take an example: Request A initially sets an index of 0 in ...

Display the preloaded element as the first item using Javascript

Is there a way to prioritize the loaded elements using JavaScript? I have an array of elements that I pass to a function and make an AJAX call. While the data is loading, I display a loader (.gif). I want to ensure that the loaded elements are shown first ...

Add JavaScript and CSS files from the node_modules folder to enhance a static HTML webpage

Currently, my development server is set up using node's live-server. However, for production, I plan to use a LAMP server. Within my node_modules directory, I have the normalize.css file. In my index.html, I currently link to it like this: <link ...

Acquire information on specific dates from a webpage

Looking to extract dates with various formats from web pages. Utilizing the Selenium2 Java API for browser interaction and jQuery for document manipulation. Seeking solutions that cover both layers. Dates can be in different formats based on locales, with ...

Ensure that the Div element is able to wrap lines in the same way that the Span element

Is there a method to ensure that a div element wraps the lines similar to how a span does? JSFiddle for testing In this example, I utilized the span tag to create an appearance as if the text was highlighted by a yellow highlighter pen. Everything functi ...

Incorporating a new row in JQuery Datatable using an mdata array

I am currently using a datatable that retrieves its data through mData. var processURL="path" $.ajax( { type : "GET", url : processURL, cache : false, dataType : "json", success ...

What is the best approach to styling a sub-child element within the first child using TailwindCSS?

Currently working with React (Next.js) and TailwindCSS. <ul> <li> <h1 className="bg-red-400">first</h1> </li> <li> <h1 className="bg-green-400">second</h1> </li> &l ...

For a while now, I've been attempting to transform my paragraph into a block within a section that showcases elements in an inline-flex layout

I have been attempting to adjust the paragraph with the errorDate class so that it displays as a block element directly beneath the input element similar to the image provided here. The section is currently set to appear as an inline-flex. Below is the CS ...

How to implement AJAX pagination in Select2 version 4

Is there a way to paginate results (every 25 rows) using Select2 4.0? I'm not sure how to achieve this. Any suggestions? If the user reaches the end of the initial 25 rows and there are more rows available, I would like to load and display them. Bel ...

What are some strategies for efficiently displaying a large amount of data on a screen using Javascript and HTML without sacrificing performance?

Imagine having a hefty 520 page book with over 6,200 lines of text ranging from 5 to 300 characters each. The challenge lies in efficiently displaying this content on the screen for users to read without causing lag or performance issues. Attempting to re ...

Exclusive JQuery Mobile Styles

Although I enjoy using JQuery Mobile, I'm facing compatibility issues with my custom Javascript on the page. Despite everything functioning correctly without JQuery Mobile, adding the library causes problems that I've been unable to resolve. Ess ...