Creating a nested link structure that alters its list item background color when another list item is hovered over

Seeking assistance with a jQuery issue - can anyone spare some time to help me out?

I am attempting to change the background of a parent element when its child is hovered over, and then revert back to its default when the child's hover ends.

The current problem I am facing is that my script does not return the background color to its default state from the CSS file; when the hover is lost, the parent's background remains the altered color.

The jQuery code:

$(document).ready(function() {
    $('ul.sf-menu li li li').hover(function() {
         var currentID = "#";
         currentID += $(this).parent().parent().attr('id');

         $('ul.sf-menu li li ul').parent(currentID).css('background', 'pink');
         $('ul.sf-menu li li li').focusout().css('background', '#00467F');
    });
});

The HTML markup:

<ul class="sf-menu">
    <li id='education'><a>Education</a>
        <ul>
            <li class='education' id='6'><a href='#' title='Desktops'>Desktops</a>
                <ul>
                    <li class='education2'><a href='#' title='#'>#</a></li>
                    <li class='education2'><a href='#' title='#'>#</a></li>
                    <li class='education2'><a href='#' title='#'>#</a></li>
                </ul>
            </li>

            <li class='education' id='9'><a href='#' title='#'>#</a>
                <ul>
                    <li class='education2'><a href='#' title='#'>#</a></li>
                </ul>
            </li>

            <li class='education' id='11'><a href='#' title='#'>#</a>
                <ul>
                    <li class='education2'><a href='#' title='#'>#</a></li>
                </ul>
            </li>

            <li class='education' id='14'><a href='#' title='#'>#</a>
                <ul>
                     <li class='education2'><a href='#' title='#'>#</a></li>
                     <li class='education2'><a href='#' title='#'>#</a></li>
                     <li class='education2'><a href='#' title='#'>#</a></li>
                     <li class='education2'><a href='#' title='#'>#</a></li>
                </ul>
            </li>
        </ul>
    </li>
</ul>

Appreciate any insights on this issue. Thank you in advance!

Answer №1

Follow the recommended jQuery syntax provided below, which includes both an In and Out handler:

http://api.jquery.com/hover/#hover1

.hover( handlerIn(eventObject), handlerOut(eventObject) )

Answer №2

My suggestion in the comment is to take advantage of the hover feature offered by jQuery. Simplify your selectors and use jQuery's capabilities to easily navigate through the DOM. For example, you can effortlessly access the parent element of a list item with just a few lines of code (there's a helpful example in the documentation). Take a look at this demo that demonstrates what I think you're trying to achieve. If it's not correct, please let me know so I can make adjustments.

To explain the code further:

$(function() {
    $('li').hover(function() {
        $(this).parent().css('background-color', 'pink');
    }, function() {
        $(this).parent().css('background-color', 'white');
    });
});

The code sets up two functions for when a list item is hovered over: one for mouseenter and one for mouseleave. Simply specify how the DOM should update based on these events. As a result, hovering over an li element will change the background color of its parent as desired.

Answer №3

  • Implement jQuery's hover function with two arguments - the first named mousemove and the second named mouseout. Use the first argument to apply your desired CSS styles, and use the second argument to remove or reset those styles.
  • To revert the CSS back to its original stylesheet values, simply set it to ''.

For a live example, click here: http://jsfiddle.net/SF3Tz/

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 correct way to utilize Bootstrap grid offsets?

Recently, I have been working on a webpage that features a unique layout using Bootstrap grid rows. Each row consists of a paragraph of text and an image. The layout is designed to have the text occupy specific columns on large screens, with the image shif ...

Find the elements of <a> tags specifically without the attribute href

Currently, I am extracting the class of all <a> elements in an HTML document of a webpage using VB.net from a WinForm: Dim htmlLinks As HtmlElementCollection = WebBrowser1.Document.GetElementsByTagName("a") For Each link As HtmlElement In htmlLi ...

Responsive Grid with Card component using React Material UI

Struggling to devise a responsive grid layout with same height cards featuring images in a React and Material-UI setup. After hours of tinkering, the "flex" part is proving to be quite puzzling. Seeking guidance. The code snippet in question: const useSt ...

The link button became unresponsive as soon as I implemented CSS changes

I customized one of my buttons with special styling, and now I'm facing an issue where the button is clickable but it fails to direct me to the intended link (which should open a YouTube video in a new tab). #help { background-color: cornflowerbl ...

Ways to adjust the visibility of a div element multiple times using javascript and css

I implemented a popup feature in my application: <div id="modal"></div> let modal = document.getElementById('modal') modal.innerHTML = ` <button class="close-button" onclick="close_modal()" ...

Advantages of incorporating CSS modules into React/Vue development

I am curious about the advantages of incorporating CSS Modules into projects with React/Vue. At my workplace, developers currently utilize the following approach during development: return ( <div className={styles.User}> <div classNam ...

Distribute the text evenly on either side of the center

I have a unique layout with two datalist elements centered, text positioned above, and two buttons integrated. body { background-color: DarkGray; } h1 { color: black; font-size: 30px; font-family: 'lucida console' } span { color: #4434 ...

Trouble exporting to Excel on Chrome and Firefox browsers

I am having an issue with exporting tables to Excel using JS. The <table> tag contains some descriptions and a class (<table class="someClassName" border="0" cellpadding="0" cellspacing="0">). When the table is exported to Excel, the Excel fil ...

Real-time Updates for JQueryUI Tooltip on Mobile Devices

I have a follow/unfollow button with jQuery UI tooltips that display the button's title. I want to update the tooltip content immediately when the button is clicked, without requiring the user to move their mouse away and back over the button. Here is ...

I'm encountering an error with the *ngIf directive in my Angular reactive form - any ideas on

Despite my reputation, I have a question that is causing me some confusion. I am trying to create a reactive form using an example on Stackblitz. While everything seems fine in Stackblitz and the code works correctly there, I encounter an error in VS Code ...

Preserve the location of selected text in an HTML document with the help of

Is there a way to retrieve the character positions of the start and end of a selected text using window.getSelection() within the HTML code? This data would need to be saved to the server for future reference. ...

How can I eliminate the error message "WARNING: no homepage content found in homepage.md"?

Starting my journey with KSS utilizing Keith Grant's CSS in Depth as a guide. In section 10.1.4, the author suggests: To begin, create a new markdown file named homepage.md inside the css directory. This file will serve as an introduction to the patt ...

The scrollbar remains unresponsive and fixed until the screen size is adjusted

Need some assistance with a website project for a client. The scrollbars on each page are not loading or changing height until the window is resized. I have a jQuery scrollbar in place, but disabling it does not solve the issue as the normal scrollbar beha ...

`Changing the iframe content dynamically with next and previous buttons: a step-by-step guide`

function displayPDF(fileSlNo){ var data = { pageMode: "PDF_DISPLAY", fileSlno: fileSlNo }; var d = $.param(data); var request = $ .ajax({ type: "GET", url:"folderNavigation.do?"+d, dataType : "TEXT", success: functio ...

Pause animation when the mouse leaves the screen

After searching through various resources, I couldn't find a definitive solution to my issue. The problem I am facing is that when the .mouseenter(function(){ }) function is triggered, and immediately followed by the .mouseleave(function(){ }) functio ...

Showing pictures from a database utilizing PHP and HTML

I'm looking to showcase the images stored in my database within an HTML table. The files are saved as 'BLOB' and I want them to appear under the 'Photo' column. Can anyone guide me on the code needed to display these images? ...

What is preventing jQuery 3 from recognizing the '#' symbol in an attribute selector?

After updating my application to jQuery 3, I encountered an issue during testing. Everything seemed to be working fine until I reached a section of my code that used a '#' symbol in a selector. The jQuery snippet causing the problem looks like th ...

display the designated image as a priority

I am designing a loading screen for my website that includes the loading of multiple images, scripts, and other elements. While the HTML and CSS part is working well, I need to ensure that the "loading..." image is loaded before anything else on the page. ...

Arranging Multiple DIVs Next to Each Other with Middle Vertical Alignment

We are facing the challenge of aligning multiple DIVs side by side while centering the content vertically. Using FLOAT or INLINE-BLOCK makes it easy to place the DIVs alongside each other, but vertical alignment becomes a problem. Any suggestions on how to ...

Loop through a JSON object and add each item to a DIV using the appendChild method

Let's say I have a JSON object, for example: { Name: "John", LastName: "Smith"} I want to display this information in a DIV element on my HTML page. Here is how it should appear: <div id = "contents"> <div class="setting-label"> ...