Highlight the parent item when the child item is being hovered over

I am working on a menu that has 2 submenus. I want to use jQuery to highlight the item when it is hovered over. However, I am struggling with how to also highlight the parent item when the cursor is on the child item. The class I am using for highlighting is called "vertical-active":

.vertical-active {
background:#0F6;
}

The jQuery function I have so far looks like this:

$(document).ready(function (e) {
$('.submenu a').hover(

function () {
    $(this).addClass('vertical-active');
    $(this).parent('.vertical-links a').addClass('vertical-active');
    },

    function () {
        $(this).removeClass('vertical-active');
        $(this).parent('.vertical-links a').removeClass('vertical-active');
    });
});

The issue seems to be with the parent selector, and I am unsure of how to correctly select the parent item of the submenu.

JSFiddle link:http://jsfiddle.net/6g9tZ/4/

Answer №1

$(document).ready(function() {
    $('.submenu a').on('mouseenter mouseleave', function() {
        $(this).add($(this).closest('ul').closest('li').children('a')).toggleClass('vertical-active');
    });
});

FIDDLE

UPDATE:

In order to highlight the parent element as well, this new code can be used:

$('.vertical-links > li > a').on('mouseenter mouseleave', function() {
    $(this).toggleClass('vertical-active')
});

FIDDLE

Answer №2

For an effective solution, utilize .siblings along with .closest.

Check out the FIDDLE here

$(document).ready(function (e) {
    $(".vertical-links > li > a").on("mouseenter mouseleave", function(){
        $(this).toggleClass('vertical-active');
    });    

    $('.submenu a').on("mouseenter mouseleave",function () {
        $(this).toggleClass('vertical-active');
        $(this).closest("ul").siblings("a").toggleClass('vertical-active');
    });    
});

Answer №3

Revise the necessary sections of your script with:

$(this).parents('li:eq(1)').find("> a").addClass('highlighted');
....
$(this).parents('li:eq(1)').find("> a").removeClass('highlighted');

An issue in your code is that you were trying to select a "parent <a>", which doesn't exist; the <a> is actually a child element of your parent. Therefore, our approach here is to locate a grandparent <li>, not the immediate parent, and then find and highlight its direct child <a>.

In addition, you initially used parent('vertical-links') when it should be corrected to parent('.vertical-links') (note the inclusion of the dot since it's a class not an element).

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

Backstretch.js experiencing issues with element functionality, but functioning correctly with body element

I'm having trouble getting backstretch to work on a div. It works perfectly when applied to the body with no errors, but when I try to apply it to a <div>, I get this error: Uncaught TypeError: Object [object Object] has no method 'backs ...

How can we effortlessly generate a times table using For loops and arrays?

As someone new to JavaScript, I am eager to learn. My goal is to create two "for" loops: one to save the values of the 6 times table up to 12x6 into an array called timesTable, and another to display these values in the console (e.g., 0 x 6 = 0). Thank y ...

Troubleshooting: Resolving the Issue of Undefined Property Reading Error

I am currently working on a code snippet to render filtered data: const tasks = [{ task: "Complete homework", description: "Math and Science assignments." }, { task: "Walk the dog", description: "Take him for a stroll in the park." }, { ...

The functions Show() and Hide() may not work in all scenarios within jQuery

I'm currently developing a website that allows users to participate in quizzes. Each quiz consists of 20 questions divided into three sections: 1 mark for 10 questions, 2 marks for 5 questions, and 4 marks for 5 questions. For each question, there are ...

Using Highcharts within a Vue.js component

I'm having trouble creating graphical components with Highcharts and Vue.js because I can't figure out how to dynamically set the id attribute that Highcharts needs to render properly. Does anyone know how to set the id dynamically? This is the ...

Can you explain the process of accessing data from [[PromiseValue]] while utilizing React hooks?

My current challenge involves fetching data from an API and utilizing it in various components through the Context API. The issue arises when I receive a response, but it's wrapped under a Promise.[[PromiseValue]]. How can I properly fetch this data ...

New Angular Datatables used to create a revitalizing table

In my project, I am utilizing the Angular Datatables library. The data is fetched from a URL that returns a JSON object, which is then stored in an array and used to populate a table. appenditems(){ this.items = []; this.items2 = []; this.items ...

Create a border surrounding the matColumn within a sticky matTable

I am currently working with a matTable that has the first two or three columns set as sticky. However, I am facing an issue where the scrolling behavior of the non-sticky columns under the sticky ones looks like a glitch due to existing border styling on t ...

What is the best method for automatically closing the modal window?

I implemented a modal window on my website. Within the modal, there is a green button labeled "Visit" which triggers the "Bootstrap Tour". I aim for the modal to automatically close when the tour starts. To access this feature on my site, users need to ...

Tips for enabling the `ignoreUndefinedProperties` feature in Node.js

I'm currently in the process of creating a REST api for my Node.js and Express application. However, I keep encountering an error stating that properties are undefined whenever I attempt to send a request. How can I go about enabling 'ignoreundef ...

Prisma unexpectedly updates the main SQL Server database instead of the specified database in the connection string

I have recently transitioned from using SQLite to SQL Server in the t3 stack with Prisma. Despite having my models defined and setting up the database connection string, I am encountering an issue when trying to run migrations. Upon running the commands: ...

Module specifiers that are considered relative must always commence with either "./", "../", or just "/"

I need help with importing three.js. I have been following the documentation but I keep encountering an error message: Uncaught TypeError: Error resolving module specifier “three”. Relative module specifiers must start with “./”, “../” or “/ ...

Automating testing with JavaScript and Selenium WebDriver

Can testing be automated using the combination of JavaScript and Selenium? I am not familiar with Java, Python, or C#, but I do have expertise in Front-End development. Has anyone attempted this before? Is it challenging to implement? Are there any recom ...

The resource was treated as an image but sent with the MIME type application/octet-stream

Upon accessing my webpage, a warning message is displayed: Resource interpreted as Image but transferred with MIME type application/octet-stream The images on my page are in JPEG format. The server writes the image bytes to an output stream and sends it ...

Difficulty recognizing sessions in production for a self-hosted Next.js application using Clerk Dev Auth

Having trouble finding the next step in debugging as I couldn't resolve the issue on Clerk's Discord or GH Issues. It seems like it might be a Next.js problem rather than a Clerk one? I am currently running a self-hosted next.js app in a docker ...

Obtaining the anchor from the list item that shares the same ID as the cell

In the following HTML code for TD, it is appended after matching the IDs from the LI HTML code below. <td style="border-top-style: solid; border-right-style: solid; border-left-style: solid; border-bottom-style: solid" id="Communication"> Co ...

Collaborating on a single instance across several processes

I have a messaging bot in my project, where the connection is established using a class instance. class MessagingBot { public bot; constructor() { this.bot = new TelegramBot(); } } export default MessagingBot; In another file, I create an inst ...

Creating a dynamic JSON object and retrieving the response in a JSP for data-driven documents

I am a beginner with the D3 API and I need to create a tree-like structure using a JSON file with hardcoded values. Additionally, I have a servlet that retrieves some values from a database which I want to dynamically convert into JSON in the servlet and s ...

Unable to establish an external connection with the node

Currently, I am in the process of establishing a connection to a local server and running an app on port 8080 using node. Both node and apache are installed on my system. When Apache is active, I can access the server externally. However, when Node is runn ...

javascript conceal other sections upon hovering

There are 4 list items (<li>) that I want to use as triggers for linked images. In this project, I am using vanilla JavaScript as jQuery is not allowed. Below is the code snippet: var children = document.querySelectorAll('#resistorContent > ...