JQuery - Triggering mouseenter/hover event only on top-level menu items, excluding the nested submenu items (list items that are not within nested lists)

I have a complex navigation menu structure with nested lists, and I'm struggling to trigger an event only on the top-level items when hovered. Despite trying different jQuery selectors and methods, such as using the NOT selector or targeting direct children, I haven't been successful.

$('.#primary-menu > li').mouseenter(function() {
    console.log('please work');
}); 

The code above triggers the event for submenu items too, which is not the intended behavior.

If anyone can provide guidance or solutions, it would be greatly appreciated.

For reference, here's a simplified example:

https://codepen.io/lol4000/pen/VwMLOMO

//**UPDATE**//

I attempted suggestions by @CertainPerformance but ran into issues due to the limitations of the WordPress platform. Using the .menu-item-has-children class instead also didn't yield the desired results.

$('.menu-item-has-children').on('mouseenter', () => {
  console.log('top-level item entered');
});

An alternative approach like the one below also didn't achieve the desired outcome:

$('#primary-menu > li').on('mouseenter', (e) => {
  console.log('top-level item entered:' + e.currentTarget.children[0].textContent);
});

Here's a snippet of the actual HTML code:

[Actual HTML code would go here]

Answer №1

It is recommended not to use the descendant selector with a space, as it will apply the listener to all descendants that match the following selector (including nested elements). Instead, use > to target direct children.

The main <ul> is identified as #primary-menu, so you should use #primary-menu > li to select its immediate children.

$('#primary-menu > li').on('mouseenter', (e) => {
  console.log('top-level item entered:' + e.currentTarget.children[0].textContent);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="primary-menu" class="menu nav-menu">
  <li id="menu-item-4793" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-4793">
    <a href="#" class="menu-image-title-after menu-image-not-hovered"><img width="1" height="1" src="https://staging.heuristic-hypatia.91-134-228-53.plesk.page/wp-content/uploads/2021/12/Plan-de-travail-1-copie.svg" class="menu-image menu-image-title-after" alt="" loading="lazy"><span class="menu-image-title-after menu-image-title">Faculty</span></a>
    <ul class="sub-menu">
      <li id="menu-item-4908" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-4908"><a href="https://staging.heuristic-hypatia.91-134-228-53.plesk.page/la-faculte-2/origine-vocation-internationale/">Presentation</a></li>
      <li id="menu-item-4893" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-4893"><a href="https://staging.heuristic-hypatia.91-134-228-53.plesk.page/la-faculte-2/origine-vocation-internationale/">Our strengths</a></li>
      <li id="menu-item-4892" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-4892"><a href="https://staging.heuristic-hypatia.91-134-228-53.plesk.page/la-faculte-2/">Graduates' career paths</a></li>
    </ul>
  </li>
  ...
  // Additional menu items and submenus
  ...
</ul>

Answer №2

It is logical that the sub-menu li is being affected by your listener since it is still nested within the parent li.

Implementing this solution should resolve the issue:

$('#primary-menu > li > a').on('mouseenter', (e) => {
  console.log(e.target);
});

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

Guide to creating a production build for electron with react js and next framework

Currently, I am working with electron using react js and next. I am struggling to figure out how to create its production build. Can someone provide me with assistance along with a detailed step-by-step guide? app node_modules pages routes static packa ...

Exploring different methods for drawing a polygon by iterating through JSON values

I am attempting to automatically draw a polygon using values stored in a database. The Python file I have returns JSON results to an AJAX call. In the AJAX success section, I need to iterate through the JSON data and automatically draw a polygon on a Googl ...

ng-Pattern in AngularJS

Enter a number as your username in the field below: <fieldset class="col-sm-12 col-xs-12 text-center"> <label for="username">Username</label> <input type="text" id="username" ng-pattern="/^[0-9]*$/" ...

Prevent a dynamically generated text input from being used if it exceeds a specific character limit in VUE.JS

I am currently working on a Vue template that dynamically creates Bootstrap text inputs. The goal is to allow the user to retrieve the values onSubmit from these inputs. One requirement I have is to disable an input if the length of the text exceeds 10 ch ...

Unable to process JavaScript function

Still in the process of developing my "mvc/social" PHP project, I am currently focusing on securing user input for the status message. I have created both a PHP and JavaScript function for this purpose, but it seems like the JavaScript function is not bein ...

Guide on utilizing angularjs $q.all() method with a dynamically generated set of promises

I am currently facing an issue with using $q.all() to wait for multiple promises to be resolved. I have created an array of promises and passed it to the all() method, but it doesn't seem to be working as expected. The promises in the array are gener ...

Executing a C++ application within a web browser

I'm looking to integrate my C++ program that generates random sentences from a word bank into my personal, low-traffic website. Ideally, visitors could click a button and see a new sentence displayed on the page. What would be the easiest way to accom ...

"The interplay of Vue components: exploring the relationships, lifecycle hooks

Brand new to utilizing Vue.js. I am exploring the concept of having a single parent component and two child components that need to communicate asynchronously through Vue's event bus system. This involves using a dummy Vue object as a shared container ...

Reading and decoding JSON data using AJAX

Upon viewing the console, I receive the JSON data in the following format: [Object] 0: Object address: "soham" region: "soham" relevanceScore: "4" startDate: "2015-05-10" subscriptionType: "1" verificationStatus: "1" __pro ...

What is the best way to make the div inside the table cells expand to fill the available space?

I'm having trouble making the inner divs within table cell divs expand and fit their parent div without overlapping the next cell below it. Check out the sandbox for reference I've outlined the areas in grey where I want the cells to be filled. ...

Converting Markdown to HTML using AngularJS

I'm utilizing the Contentful API to retrieve content. It comes in the form of a JSON object to my Node server, which then forwards it to my Angular frontend. This JSON object contains raw markdown text that has not been processed yet. For instance, t ...

"Error: The req.body object in Express.js is not defined

edit:hey everyone, I'm completely new to this. Here's the html form that I used. Should I add anything else to this question? <form action="/pesquisar" method="post"> <input type="text" id="cO" ...

Invoke a method in an Angular 2 component using an HTML event

Can an angular component method be invoked using an HTML event? <shape onclick="myMethodInParentComponent()" > I am unable to use (click) as shape is not recognized by Angular. Shape also contains several unknown sub elements making it impractical ...

Hide dropdown when clicked outside of it

Can someone help me modify my JavaScript code so that when I click on a new dropdown, it closes the previous one and keeps only the current one open? function manageDropdowns() { var dropdowns = document.querySelectorAll('.dropdown:not(.is-hove ...

The storage of HTML5 data is not being saved locally

<html> <head> <title></title> <style type="text/css"> body { font-family: tahoma; } h2 { font-weight: bold; border-bottom: 2px solid gray; margin-bottom: 10px; } #dat ...

Is it feasible to execute a cross-site request forgery attack on a URL that delivers a JSON object as a response?

I am aware of the potential for a Cross-Site Forgery Attack that can target requests returning arrays by manipulating the Array constructor. For instance, let's say I have a site with a URL: foo.com/getJson that provides the following array: [&apos ...

What is the best way to properly format the retrieved JSON string using Ext JS?

After receiving the JSON data shown below, I need to change the formatting of the string values in the 'code' field. For example, 'TOTALPENDING' should display as "Pending Bonus" and 'TOTALLEFT' as "Current Bonus". How can I m ...

What is the best way to display a list of items in Vue JS while maintaining the

Looking to display my Vue.js list in reverse order using v-for without altering the original object. The default HTML list displays from top to bottom, but I want to append items from bottom to top on the DOM. Telegram web messages list achieves this wit ...

Transferring NodeJS information to JavaScript

I am currently working on a web application where the client receives data from a server. The challenge I'm facing is how to pass this data from NodeJS to a Javascript file that is included in an HTML document. Unfortunately, I have not been successfu ...

Forwarding requests via middleware in next.js 13 AppDir: true

I am currently working on implementing a redirect feature in next.js 13 when the jwt back-end is not received. This is being done with the appdir activated. This is the code in my middleware.ts file: import { NextResponse } from 'next/server' im ...