Hide and show submenus with jQuery while ensuring that the initial submenu remains visible, along with the main menu

I am struggling to figure out how to make the first message active by default along with its corresponding menu selection in my navbar. I have implemented a show/hide functionality on the main menu click, but currently only the menu is being set as active while the message is displayed only when clicked.

This is the structure of my HTML:

<ul class="nav justify-content-center ">
  <li class="nav-item active main-menu">
    <a class="nav-link " href="#">Mango</a>
    <div class="msg active">
      <p class="position">You selected Mango</p>
    </div>
  </li>
  <li class="nav-item main-menu">
    <a class="nav-link " href="#">Banana</a>
    <div class="msg">
      <p class="position">You selected Banana</p>
    </div>
  </li>
  <li class="nav-item main-menu">
    <a class="nav-link " href="#">Grapes</a>
    <div class="msg ">
      <p class="position">You selected Grapes</p>
    </div>
  </li>
</ul>

Below is the javascript code that handles the functionality:

//add remove class
$(".nav li").on("click", function() {
  $(".nav li, .nav li a").removeClass("active");
  $(this).addClass("active");
})
//show hide message
$(".main-menu .msg ").hide();
$(".main-menu a").click(function() {
  $(".main-menu .msg").hide('fast');
  $(this).parent().find("div").toggle("fast");
})

Currently, only the first menu is active and the message is displayed only on its click event. I need assistance on how to display the first message by default or ensure it is active along with its menu selection.

Answer №1

After analyzing your query, it seems like you are looking to have the first menu item open by default on initial load. To achieve this, you will need to make some adjustments in your code. Remove the line that hides the message div using jQuery and instead apply CSS styling to hide it initially. Then, add an 'active' class only to the first message div and reveal it through CSS.

//add remove class
$(".nav li a").on("click",function(){

$(".nav li a").removeClass("active");
$(this).addClass("active");

$(".nav li a").not(this).next().slideUp();
$(this).next().slideToggle();
});
.msg {
display: none;
}
.msg.active {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="nav justify-content-center ">
<li class="nav-item active main-menu">
<a class="nav-link active" href="#">Mango</a>
<div class="msg active"><p class="position">You selected Mango</p></div>
</li>
<li class="nav-item active main-menu">
<a class="nav-link " href="#">Banana</a>
<div class="msg"><p class="position">You selected Banana</p></div>
</li>
<li class="nav-item active main-menu">
<a class="nav-link " href="#">Grapes</a>
<div class="msg"><p class="position">You selected Grapes</p></div>
</li></ul>

Answer №3

Implemented a new id #labl in the message div and made some adjustments as outlined below.

$(".lab .msg ").hide();
$(".lab #labL ").show();
$(".lab a").click(function () {
$(".lab .msg, .lab #labL").hide('fast');
$(this).parent().find("div").toggle("fast");
})  

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

Show information when table is clicked

I currently have a 9 x 9 table with unique content in each cell. Is there a way to enable the following functionality: Upon clicking on the text within a specific cell, all related content would be displayed right below that same cell? For instance, if ...

Executing the fadeIn() callback in JQuery before the animation finishes when invoking a function

I've noticed quite a few posts discussing this issue on the site, but most of them focus on multiple animations. After trying some solutions, I have narrowed down my problem to one specific box that I'm attempting to fade. Strangely enough, when ...

Switching the navigation menu using jQuery

I am looking to create a mobile menu that opens a list of options with a toggle feature. I want the menu list to appear when the toggle is clicked, and I also want to disable scrolling for the body. When the toggle menu is clicked again, the list should c ...

Exploring Node and Express Request Query

I'm struggling with a specific endpoint setup in my code. // GET /api/logs/ app.get('/api/logs', function (req, res) { if (req.query.reverse === true) { res.send((mainModule.logs).reverse()); } else { res.send(mainModule.logs) ...

When a user taps on a link or anchor within a specific webpage on an iPhone, the font size will automatically increase

The issue is specific to iPhones. I have tested it on an iPhone 5 (landscape mode) and an iPhone 4s (landscape mode). For a visual demonstration, you can view the video here. I attempted to fix the problem by specifying the font size, but unfortunately, ...

Addressing duplicate CSS issues in Firebug?

CSS: .list-a .desc-fix { width: 180px; margin: 0px auto; position: relative; } .list-a .desc { background: url("../images/trans_black.png") repeat; display: block; font-family: arial; font-size: small; height: 18px; mar ...

Ways to customize weekend colors in v-calendar (distinct colors for Saturdays and Sundays)

Looking to customize the appearance of weekends in your calendar by changing their colors? I have a component for the v-calendar that can help with that. Here's the code: <div id='app'> <v-date-picker title-position="left&quo ...

Creating a dynamic navigation bar that adjusts to changing content requires careful planning and implementation

Struggling with achieving my visual mockup while designing a webpage: Check out my web design mockup Currently focusing on section 2 of the page. Using Angular 5, Bootstrap 3, and ngx-bootstrap library to integrate Bootstrap components into Angular. Here ...

Step-by-step guide on showcasing a quiz utilizing Magnific-popup and ajax

My goal is to create a functionality that allows users to easily download and view a quiz in a lightbox with just one click. I have successfully set up the ajax features and believe I am using Magnific-popup correctly, but for some reason, the lightbox is ...

Combining multiple arrays in Node.js to create a single JSON file

I'm exploring the world of nodejs and currently working on creating a Json parser that will pull data from a Json API, allow me to access specific data points (some of which will need transforming), and then save it to a Json file. I recently came ac ...

express.static() fails to serve files from public directories when accessed via router paths other than "/"

Express static configuration: app.use(express.static(__dirname + "/public")); Directory Structure: --public --assets --js --[JavaScript scripts] --stylesheets --[CSS files] Defined Routes: const shopRoutes = require('./routes/shopRo ...

Align two columns using the vertical alignment feature in the Bootstrap grid system

Is there a way to horizontally align an element within a bootstrap grid? In the code snippet below, I have a col-md-4 and another col-md-8 that I would like to vertically align in the middle, as shown in the image. Click here for a demonstration. This is ...

Implementing a smooth camera movement in Three.js using the mousewheel

Is there anyone who can assist me with achieving smooth camera movement (forward/backward) using the mouse wheel? The current code I have is not providing the desired smoothness. document.addEventListener( 'mousewheel', onDocumentMouseWheel, fal ...

get value from json with specified key

Here is a function that handles the success of my AJAX call: success: function(responseJson) { var receivedData = []; $.each(responseJson.jsonArray, function(index) { $.each(responseJson.jsonArray[index], function(key, value) ...

Setting the default date in angular-bootstrap-datetimepicker: a step-by-step guide

I am currently utilizing the angular-bootstrap-datetimepicker module for allowing users to choose a date and time. How can I set a default date and time when the view initially renders? Is there an attribute available that allows us to assign a boolean val ...

Utilizing dynamic content to pass arguments to JavaScript functions

I'm facing a challenging issue that is causing me frustration. While browsing through this platform, I found some potential solutions but encountered a roadblock in implementing them successfully. My current project involves developing an e-commerce p ...

Is it possible to retrieve the controller path for an AJAX request from within a partial view?

Looking for a solution to fully decouple and reuse a partial view that allows users to select dates and filter results based on those dates. This widget can be used on multiple pages, so I wanted to add event listeners that would submit the form within the ...

Manipulate Browser Navigation Behavior using JavaScript or AngularJS

How to Manage Browser Back Button Behavior Using AngularJS or JavaScript This is not a question, but rather a demonstration of how you can disable and manipulate the behavior of the browser's back button when using AngularJS or plain JavaScript. ...

Ensure that the text within the ng-repeat is wrapped in a span element and each

When using ng repeat in span, I encountered a word breaking into a new line. Here is the actual output: https://i.stack.imgur.com/k4c9k.png To style this, I implemented the following CSS: border: 1px solid #ECE9E6; border-radius: 3px; text- ...

The image filter plugin is functioning properly in one project, however, it is not working in

After successfully using a plugin from w3schools to filter elements in one project, I encountered an issue when attempting to implement it in another project. Here is the link to the problematic code pen: https://codepen.io/zakero/pen/mZYBPz If anyone ca ...