Maintain the highlighting of the parent menu item even when hovering over the submenu (HTML/CSS/Jquery)

Having a menu with the potential for subitems, it seems simple enough. The goal is to highlight the parent menu item once the submenu is moused over. Unfortunately, this doesn't happen as expected because the browser reverts back to its default style when the mouse moves from the menu item to the submenu. Any assistance would be greatly appreciated! Thank you!

Menu HTML:

<div id="top_navigation">
        <ul>
            <li><a href="#">item1</a></li>
            <li><a href="#">item2</a>
                <ul class="submenu">
                    <li><a href="#">sub1</a></li>
                    <li><a href="#">sub2</a></li>
                    <li class="selected_menu_item"><a href="#">sub3</a></li>
                </ul>
            </li>
            <li><a href="#">item3</a></li>
            <li><a href="#">item4</a></li>
        </ul>
    </div>

CSS:

#top_navigation {
    width: 1248px;
    margin: 0 auto;
    position: relative;
    text-transform: uppercase;
    font-family: "Rounded Font", sans-serif;
    font-size: 23px;
}
#top_navigation ul ul {
    display: none;
}
#top_navigation ul {
    padding-left: 0;
}
#top_navigation ul li {
    margin: 0;
    padding: 0;
    float: left;
    width: 312px;
    height: 64px;
    line-height: 64px;
    font-size: 20px;
    list-style: none;
}
#top_navigation ul li a {
    display: block;
    text-align: center;
    text-decoration: none;
    color: #eb1f10;
    background-color: #FFF;
}
#top_navigation ul li.selected_menu_item a {
    background-color: #eb1f10;
    color: #FFF;
}
#top_navigation ul li a:hover {
    background-color: #eb1f10;
    color: #FFF;
}
#top_navigation li li {
    height: 42px;
    line-height: 42px;
    border-top: #eb1f10 1px solid;
}

JS/Jquery:

$(document).ready(function () {
    var $nav = $('#top_navigation > ul > li');
    $nav.hover(
        function() {
            $('ul', this).stop(true, true).slideDown('fast');
        },
        function() {
            $('ul', this).slideUp('fast');
        }
    );
});

Visit this link for an example: http://jsfiddle.net/qguTz/

Answer №1

It's amazing how sometimes the simplest solution can evade us for so long... But here it is:

All you need to do is replace this bit of code:

#top_navigation ul li a:hover {
    background-color: #eb1f10;
    color: #FFF;
}

with this:

#top_navigation ul li:hover > a {
    background-color: #eb1f10;
    color: #FFF;
}

Answer №2

To accomplish this, you just need to make a couple of small tweaks.

Firstly, update the CSS by adding a new selector to an existing style declaration:

#top_navigation ul li a:hover, #top_navigation ul li a.hovered {
    background-color: #eb1f10;
    color: #FFF;
}

Next, modify the CSS to incorporate that class:

$nav.hover(
    function() {
        $(this).children('a').addClass('hovered')
        $('ul', this).stop(true, true).slideDown('fast');
    },
    function() {
        $(this).children('a').removeClass('hovered')
        $('ul', this).slideUp('fast');
    }
);

After implementing these changes, everything should be working as intended! Check it out here

Answer №3

Check out this cool JSFiddle code snippet!

$nav.hover(
    function() {
        $('ul', this).stop(true, true).slideDown('fast');

        $('a',this).first().css({"background-color":"#eb1f10", "color":"#FFF"});
    },
    function() {

        $('ul', this).slideUp('fast');
       $('a',this).first().css({"background-color":"#FFF", "color":"#eb1f10"});
    }

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

What is the best way to ensure consistent code placement at the bottom of my Django Template using inheritance?

Lately, I've been working on incorporating a footer into my layout.html file that is inherited by all other pages within my Django project. I am aiming to create a footer that remains fixed at the bottom of every webpage just like how Stack Overflow ...

The localization feature in jQuery mobile is causing the button style to disappear

For my current project, I am utilizing the jquerymobile framework along with the i18Next localization library. Here is the HTML code snippet: <div id="messageboxPage" data-role="page" data-theme="a"> &l ...

Unable to prevent ordered lists from overlapping with other content I attempt to place beneath them in HTML

function filterImages() { let input = document.getElementById('searchbar').value; input = input.toLowerCase(); let images = document.getElementsByClassName('gallery'); for (let i = 0; i < images.length; i++) { ...

Struggling to update the inner HTML of a <p> tag using LocaleDateString() function

Recently, I've been experimenting with creating a calendar but encountered a frustrating issue. I created a variable storing a date using the toLocaleDateString method. However, when attempting to modify a paragraph's inner HTML, nothing seemed t ...

When the LI element is clicked, it triggers the display of another LI element without affecting the rest of the

New to the web development scene and trying to figure out how to create a collapsible text feature using HTML, JavaScript, and JQuery. I've got the styling down but struggling with the scripting part. Here's an example of what I'm trying to ...

Using jQuery to extract a specific dropdown control from a collection of dropdown controls within a table row

I'm facing an unusual situation. There's a table with multiple rows (each generated dynamically by clicking a button). Each row contains the following: |=======| |=======| |=======| |=======| Where |=======| represents a dropdown se ...

What is the best way to define the width of a value in percentage using JavaScript's

Here's a snippet of code that I'm working with: <div id="test-content"></div> <script> var width = 100; document.getElementById('test-content').style.width = width+ '%'; </script> I encountered an iss ...

Using jQuery to Validate if a Date Input Field is Empty

Currently, I have the following code snippet. $('form input[name="birthDate"])').blur(function () { var dob = $("#dob").val(); if(dob == "") { $("#dobAlert").show(); $("#laba").attr("disabled", true); } else ...

The CSS styles are not recognized by the Windows 2003 server

After deploying my webapp, which was created using asp.net, to a testing server (Windows 2003 SP2, IIS6), I encountered an issue. When I accessed the default page, none of the CSS styles were applied. Only plain text or formatting from the .aspx file was v ...

How can you determine if a user has selected "Leave" from a JavaScript onbeforeunload dialog box?

I am currently working on an AngularJS application. Within this app, I have implemented code that prompts the user to confirm if they truly want to exit the application: window.addEventListener('beforeunload', function (e) { e.preventDefault ...

Toggle between signing in and signing out

Earlier today, I posed a question regarding a functionality I am trying to implement. Despite receiving suggestions from various members, I have been unable to achieve my desired outcome. Here is some additional context. I am attempting to create a toggle ...

Is the imported style file not properly scoped?

Whenever I attempt to import a CSS file using this method, the styling is not properly scoped. Is it necessary to write the styles within a style tag for them to work correctly? I have been experimenting with this in Vue-cli. <style scoped> @im ...

What are the steps to view my HTML webpage on a smartphone?

Recently, I successfully created an HTML webpage with CSS and JS that looks and functions perfectly on my PC. However, when attempting to access it on my phone, I encountered some issues. Despite transferring all the necessary files to my phone, only the ...

Is there a way to eliminate the whitespace beneath the "Brilliant" division?

[Screenshot of white space under div] [1]: https://i.sstatic.net/cO7TV.jpg I'm having trouble figuring out why there is visible white space here. As a coding beginner, I would really appreciate any assistance. I've tried searching for the soluti ...

Using Jquery to retrieve the data-id attribute value from the <li> element

Seeking assistance on how to retrieve the value of (data-id=64) when clicking on a specific li-item within a tree structure. The tree consists of 5 list items, each with subchilds. Currently, I am able to obtain the (data-uid) of the first li, but I'm ...

Tips for including a jQuery file in your C# code using V8ScriptEngine (Clearscript)

I'm currently attempting to run a JavaScript function from C# code using ClearScript (V8ScriptEngine). The variable Script_Text contains the JavaScript code. I want to invoke an API call from jQuery and load the Execute function in C#. However, I enco ...

Add a font awesome icon dynamically using JavaScript

I'm currently working on a navigation bar in JavaScript that displays the titles of various links. However, I would like to enhance it by adding small icons next to the text. Can anyone guide me on how to integrate Font Awesome icons into my JavaScrip ...

Customize your AutoComplete with MUI styling

Upon taking over a project, I found myself working with material ui for the first time. Here is an excerpt from my code: <FormControl fullWidth> <InputLabel className={className} htmlFor={id} error={error} > ...

Place elements in a grid layout using CSS (and also ensure they are centered)

My goal is to create a data-grid (table layout) where the elements have fixed sizes. These elements should be placed in the same line until they can't fit anymore, then move to the next line. I have tried using inline-blocks for this, but I'm st ...

How to validate a <select> element with parsley.js when it is dynamically populated with an object?

I'm struggling to validate a <select> element in my form. With the help of knockout.js, I select a location which then populates the Service Point based on the Location chosen. However, when I try to validate the form using parsley.js after pres ...