Sliding Menu with jQuery

My goal is to create a dynamic menu that reveals sub-menu items by sliding them down and changing the background color upon clicking. I am currently using the HTML code displayed below, with the sub1 and sub2 elements initially hidden using display:none;

You can view the code here

However, I am facing an issue where all sub-menus open simultaneously. My desire is for only one sub-menu to be visible at a time, and when a different menu item is clicked on, the previously opened sub-menu should slide back.

<ul class="nav">
            <li class="mainnav">MAINNAV</li>
                    <li class="sub1">SUB1</li>
                    <li class="sub2">SUB2</li>
</ul>
<ul class="nav">
            <li class="mainnav">MAINNAV2</li>
                    <li class="sub1">SUB1</li>
                    <li class="sub2">SUB2</li>
</ul>

Additionally, here is the jQuery code snippet being used:

$(".mainnav").on("click", function(){
    $(".sub1, .sub2").slideDown("fast");
    $( ".mainnav" ).animate({
        backgroundColor: "#3A3A3A", 
        }, 500 );
});

Answer №1

When working with jQuery event handlers, you have access to an event object containing various helpful parameters. One of these parameters is currentTarget, which refers to the DOM element that initiated the event. This allows you to perform actions on the specific element that was interacted with, even if the original selector matches multiple elements.

$(".menu").on("click", function(event) {
    $(".submenu1, .submenu2").slideUp("fast");
    $(event.currentTarget).siblings(".submenu1, .submenu2").slideDown("fast");
    $(event.currentTarget).animate({
        backgroundColor: "#3A3A3A", 
    }, 500 );
});

Check out the updated Fiddle here: http://jsfiddle.net/abc123/7/

Additionally, if you want to animate the background color, consider using a plugin like jQuery UI. For more information, refer to this thread: jQuery animate backgroundColor

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

Enable AJAX functionality on dynamically created elements without needing to refresh the page

Although this question may have been asked in similar ways before, I am unable to identify the cause of the problem in my specific code. The issue is with a button that is supposed to toggle between "Add" and "Remove". When successful removal occurs, the ...

Maintain continuous visibility of horizontal scroll in Bootstrap responsive tables

When utilizing responsive bootstrap tables in a .net web application to showcase data, the issue arises when a substantial amount of information is returned. In such cases, a horizontal scroll bar appears at the bottom of the page. This forces users to s ...

Is there a way to retrieve the dates from last month using jQuery?

Currently, I am unable to select past dates with the provided code. How can I adjust it to allow for selecting dates from previous months? let firstDay = new Date(); $('#date_filter_startmonthly').datepicker({ startDate: firstDay, endDate: ...

Exploring the power of JQuery's asynchronous promises within a labyrinth of nested

As a newcomer to Node.js and promises (specifically using Q.js), I am attempting to create a web scraper for a site with the following structure: Main Page: contains a list of categories, each with a link leading to a page listing various stores. List of ...

Performing mathematical operations in JavaScript, rounding to the nearest .05 increment with precision up to two

Apologies in advance. After reviewing multiple posts, it seems like the solution involves using the toFixed() method, but I'm struggling to implement it. $('.addsurcharge').click(function() { $('span.depositamount&ap ...

Automate the process of launching the <select> picker through programming

In an Android WebView, I need a way to programmatically trigger the opening of the select element picker provided below. <select id="select1" multiple="multiple"> <option value="MDO1" selected="selected">MDO 1</option> <option val ...

Tips for preserving the contents of a list with HTML and Javascript

My latest project involves creating a website with a To-Do list feature. Users should be able to add and delete items from the list, which I achieved using JavaScript. Now, my next goal is to ensure that the current items on the list are saved when the pag ...

Is it possible to trigger a textbox text change event after autocompleting using jQuery

I recently implemented a jquery autocomplete plugin for a textbox: $('#TargetArea').autocomplete({ source: '@Url.Action("GetTarget", "Ads", new { type = "Zip", term = target })' }); The implementation is working as expected. ...

What causes the jQuery ready() function to activate?

I'm feeling quite perplexed at the moment. I was under the impression that jQuery(document).ready(function(){ ... }) would be triggered once the page had finished loading all its content. However, it seems that's not the case. Let me explain wha ...

To activate an underline on text, simply right-click and select "text

All the anchor tags on my website have been styled with text-decoration: none. Additionally, I have added a CSS rule based on a helpful answer: a, a:hover, a:active, a:visited { text-decoration:none; } However, whenever I right-click on a link on my ...

Margin of Google Pie Chart division

Struggling to eliminate a mysterious margin from a div generated by Google Charts, despite no defined margins in the code that could be causing it. Below is a visual representation of the problematic div: div with unidentified margin Any assistance on t ...

The jQuery onchange event does not remove the disabled attribute from HTML elements

I have been experiencing some difficulties trying to remove the disable attribute from an HTML document using the prop method. Here is a snippet of my HTML code: <form> <!-- Add your HTML code here --> </form> Currently, I am only using ...

Troubleshooting flow problems in flexbox container for

https://i.stack.imgur.com/ZpVaH.png I have implemented a flexbox-based page layout. The layout consists of two sidebars on the left and right sides, with fixed widths, and a central content panel that dynamically adjusts to fill the remaining space. Howe ...

Instructions for concealing and revealing a label and its corresponding field before and after making a choice from a dropdown menu

Currently, I am working on developing a form that will enable customers to input their order information. This form includes a selection list for payment methods, with three available options. If the user chooses either credit or debit card as the paymen ...

Move the aircraft across the display in a lively animation

I need help creating an animation where a plane flies across the screen, exits from the left side, and re-enters from the right side in a continuous loop. How can I achieve this effect to make the plane fly endlessly across the screen? Here is my code: ...

Creating a dynamic hover drop-down navigation bar in ASP.NET

After successfully creating a navigation bar with hover effects, I am now looking to implement a dropdown list when hovering over the items. Can anyone provide guidance on how to achieve this? Below is the current code snippet I am working with: <ul c ...

Column-count can result in the flex div dividing the element into two parts

Whenever I utilize column-count with nested divs that have display: flex set, I encounter a problem where elements are cut in half. The suggestion from this answer is to use display: inline-block to prevent this issue. However, when I implement that soluti ...

Attach a tab-icon to a picture

I am looking to add a tab to the bottom border of an image within a gallery. This tab needs to be right up against the image border with no space in between. When clicked, this tab should activate a small JavaScript function that will display the content ...

How can I execute a Python script on an HTML webpage by clicking a button?

Below is the HTML code I have written: <script> function goPython(){ $.ajax({ url: "MYSCRIPT.py", context: document.body }).done(function() { alert('finished python script');; ...

Modifying the innerHTML of SimpleModal and passing a parameter to a function causes an error to occur

I am currently working on a project where I have a collection of photos displayed on the index page. Each photo should trigger a modal that displays a larger version when clicked. However, I encountered an issue while attempting to use jQuery to modify the ...