Unable to display menu content text using jQuery

Currently experimenting with jQuery to create a dynamic submenu. The goal is to have a sub menu appear when the main menu is clicked, and then disappear when an item in the sub menu is selected, revealing additional information within a div. Unfortunately, I'm facing some challenges getting it to function properly.

Here's the structure of my HTML:

<ul id="menu">
    <li>
        <a href="#">Item 1</a>
        <ul id="submenu">
            <li><a href="#" data-menu="show1">Sub menu 1</a></li>
            <li><a href="#" data-menu="show2">Sub menu 2</a></li>
        </ul>
    </li>
</ul>
<div id="show1" class="content">Lorem ipsum ad his scripta blandit partiendo, eum fastidii accumsan euripidis in, eum liber hendrerit an. </div>
<div id="show2" class="content">Ius id vidit volumus mandamus, vide veritus democritum te nec, ei eos debet libris consulatu. No mei ferri </div>

And here's the jQuery code I've implemented:

$(document).ready(function () {
    $('#menu li ').click(function () {
        $('#submenu').fadeToggle();
        $('.content').fadeOut();
    });
    $('ul#submenu li a').click(function () {
        var menu = $(this).data("menu");
        $('#' + menu).fadeIn();
    });
});

The concept is simple: clicking on the menu hides all content divs and toggles the visibility of the submenu. When a submenu item is clicked, the submenu disappears and the corresponding content div based on the data attribute appears.

However, upon clicking a submenu item, the content briefly displays before disappearing again. Any insights into what might be causing this issue?

Feel free to check out the fiddle for a closer look: https://jsfiddle.net/yab34zdw/

Answer №1

Upon clicking a submenu item, both event handlers are triggered simultaneously. The issue lies within the selectors being used:

$('#menu li ') is capturing not only the menu items but also the submenu items, which are essentially <li> elements that are nested inside the menu. To rectify this, you can update the selector to $("#menu > li"), targeting only immediate children of the menu. Alternatively, it is advisable to assign classes and utilize simpler selectors.

Here is the corresponding HTML structure:

<ul id="menu">
    <li class="menu-top-item">
        <a class="menu-top-item-link" href="#">Item 1</a>
        <ul id="submenu">
            <li class="menu-sub-item">
                <a class="menu-sub-item-link" href="#" data-menu="show1">Sub menu 1</a>
            </li>
            <li class="menu-sub-item">
                <a class="menu-sub-item-link" href="#" data-menu="show2">Sub menu 2</a>
            </li>
        </ul>
    </li>
</ul>

Additionally, here is the JavaScript code with a link to the relevant Fiddle:

$('.menu-top-item-link').click(function () {
    $('#submenu').fadeToggle();
    $('.content').fadeOut();
    return false;
});
$('.menu-sub-item-link').click(function () {
    var menu = $(this).data("menu");
    $('#' + menu).fadeIn();
    return false;
});

Answer №2

It seems like there might be a way to tweak the code to get closer to what you have in mind. It appears that both click functions were focusing on your submenu content.

$(document).ready(function () {
    $('#menu .menu ').click(function () {
        $('#submenu').fadeToggle();
        $('.content').fadeOut();
    });
    $('ul#submenu li a').click(function () {
        var menu = $(this).data("menu");
        $('#' + menu).fadeToggle();
    });
})
<ul id="menu">
    <li>
        <a href="#" class="menu">Item 1</a>
        <ul id="submenu">
            <li><a href="#" data-menu="show1">Sub menu 1</a></li>
            <li><a href="#" data-menu="show2">Sub menu 2</a></li>
        </ul>
    </li>
</ul>
<div id="show1" class="content">Lorem ipsum ad his scripta blandit partiendo, eum fastidii accumsan euripidis in, eum liber hendrerit an. </div>
<div id="show2" class="content">Ius id vidit volumus mandamus, vide veritus democritum te nec, ei eos debet libris consulatu. No mei ferri </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

Uncovered event listener in Angular tests

Imagine having a custom directive: angular.module('foo').directive('myDir', function () { return { restrict: 'E', link: function (scope) { var watcher = scope.$watch('foo, function () {}); scope.$on ...

Start the BrightCove video by clicking on the link

I successfully integrated a Brightcove video into my mobile site and now I want to trigger it to play when the user clicks a link. Is there a way to access the video and start playing it using JQuery? <div id="video_player"><!-- Brightcove playe ...

Concealing Popover with internal click

I am currently implementing Vue-PopperJS in my project, following the setup provided on the linked page with a few modifications: <template> <Popper ref="popover" trigger="clickToToggle" :options="{ pla ...

Is it possible to create a return type structure in TypeScript that is determined by the function's argument?

I'm currently stuck on developing a function that takes a string as an argument and outputs an object with this string as a key. For example (using pseudo code): test('bar') => {bar: ...} I am facing difficulties in ensuring the correct ...

What is the best way to extract information from a JSON object?

I am currently utilizing the JSON.js library provided by JSON.org. <% JSONReturn = GetDistance(Sample) // this function returns a string in JSON format (specifically from the ArcGIS server Solve Route function) JSONObject = JSON.parse(JSONReturn,"Tota ...

Angular 2 event emitter falling behind schedule

I am currently utilizing Angular 2 beta 6. The custom event I created is not being captured import {Component, OnInit, EventEmitter} from 'angular2/core'; import {NgForm} from 'angular2/common'; import {Output} from "angular2/core" ...

Non-functioning function within object

this is a unique object var Manager = (function () { var self = this; self.fetch = function (request, response) { response.send({ message: 'Data fetched successfully' }); } return self; })() module.ex ...

Separating the login/register functionality from the main app using the MEAN Stack

Apologies for my poor English! I have developed an application using the MEAN stack (MongoDB + Express.js + Angular.js + Node.js) with authentication utilizing passport.js and JWT (jsonwebtoken and express-jwt). What I aim to achieve? The login and r ...

Centered text with custom images in an HTML list

I'm experimenting with customizing lists and currently using a custom list-style-image. I'd like to know how to center the text and image so they are always aligned, even in the case of multi-line text. I've included a picture for reference. ...

Create SCSS to style multiple CSS classes

Are there more efficient ways to create css helper classes like the ones shown below? Can I use scss to generate cleaner and better classes? Thank you. .m-1 { margin: 1px !important; } .m-2 { margin: 2px !important } .m-3 { margin: 3px !important } .m-4 ...

Transitioning to Firebase Authentication

I made the decision to transition away from firebase authentication. To accomplish this, I exported all firebase users along with their email addresses, hashed passwords, salt keys, and other necessary information. Next, I transferred them to a database a ...

It's recommended to utilize the callback feature with setLoggedIn to ensure the previous state is captured effectively, as illustrated below:

To ensure capturing the previous state when using setLoggedIn, it is recommended to utilize the callback option. This will help in keeping track of changes and ensuring smoother functionality: ...

What is the best way to reduce the size of a Bootstrap card image back to its original dimensions when

I am currently experimenting with a bootstrap card using HTML, CSS, and Bootstrap. My main focus right now is on how to shrink the image when hovering over it. The .card-header-img has a fixed height of 150px that I do not want to modify. What I want to a ...

Ajax: Cross-Domain Request Blocked: The Same-Origin Policy prevents access to the external resource at

I am running an MVC Web API Service on two servers. When accessing it through C# using WebClient and HttpClient, as well as through Postman or directly pasting the service URL in the browser, everything works fine. However, when trying to consume it throug ...

Troubleshooting problems with jQuery Chosen plugin post-AJAX request

I'm encountering an issue with the plugin called jquery-chosen not applying to a control that is reconstructed by an ajax call. Despite exploring other suggestions, I have yet to find a solution that works. The versions of jquery and jquery-chosen be ...

Is it advisable to incorporate multiple images onto a single canvas?

What is the best approach to handling multiple images in HTML5? Is it preferable to create a separate canvas tag for each image or is it equally effective to have multiple images in one canvas, and how would I go about doing that? Here is the code I have ...

Click-triggered CSS animations

Trying to achieve an effect with regular JS (not jQuery) by making images shake after they are clicked, but running into issues. HTML: <img id='s1_imgB' class="fragment"... onClick="wrongAnswer()"... JS: function wrongAnswer(){ docume ...

Vue.js - Displaying validation errors when a user interacts outside of a component

The ExamEditor Vue component I am working on is quite complex, consisting of sub-components like QuestionEditor and ExerciseEditor. These components are all tied to an exam object that contains nested arrays with questions and more. The layout inside the e ...

How to iterate through two objects simultaneously using a directive in Angular and Vue.js

I am facing a challenge with creating an Angular directive that can iterate over a data object and display its values along with the values of a second unrelated object with similar structure. Currently, I am developing a translation app where the origina ...

Capture a snapshot of a webpage that includes an embedded iframe

Currently, we have a nodeJS/angular 4 website that contains an iframe from a third party (powerBI Emebdded). Our goal is to develop a feature that allows the end user to capture a screenshot of the entire page, including the content within the iframe. We ...