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

Synchronized loops in jQuery using the .each method

I'm having trouble getting the ajaxStop function in jquery to work. Any suggestions on how to make it fire? My goal is to iterate through each anchor tag and update some content within it. After that, I want to use the ajaxstop event to trigger a scr ...

Pass multiple variables as input to a function, then query a JSON array to retrieve multiple array values as the output

My JavaScript function contains a JSON array, where it takes an input and searches for the corresponding key/value pair to return the desired value. I am attempting to input a string of variables like this: 1,2,3,4,5 Into this function: function getF(f ...

Tips on transitioning from Modal1 to Modal2 in Ionic after a successful submit button press?

My survey app requires users to fill out a form and click the Submit Feedback button. Upon successful submission, a message saying "Feedback submitted successfully" should be displayed in Modal2, which is inside another modal named (Modal1). However, being ...

Encountering Problem with Jmeter Script Playback - Kindly Activate JavaScript to Access Page Information

I'm currently experiencing a challenge when trying to simulate the following scenario in my JMeter script. I would truly appreciate any assistance or solutions you can offer. My goal is to create a JMeter script for a form submission process within a ...

What is the best way to apply a CSS class to newly added records within an HTML table that are being fetched from a MySQL database?

The title does not provide clear instructions. If more details are needed, the code below displays data from a MySQL database table on an HTML page: <?php $db_host = 'localhost'; $db_name = 'DB'; ...

Execute a task when every class element contains a value

$("#btn_02").click(function(){ $(".quant").each(function() { var quantity = $(this).html(); alert (quantity); // each value is 0 if (quantity == 0) {return false;} }); $.ajax({ url: "process02.php", succ ...

Is it required to double click checkboxes to uncheck them?

My checkboxes require 2 clicks to be unchecked, even though one click is enough to check them. This issue occurs in all 7 checkboxes and there is no onchange() function or similar in TS. import { Component, OnInit, Inject } from '@angular/core&apos ...

Creating a container that scrolls horizontally

I am working with ngbootstrap and angular, however, I believe the issue at hand is more related to html/css. My goal is to create a container that scrolls horizontally, despite coming across several helpful threads on this topic, I am struggling to impleme ...

Vue.js is limited in its ability to efficiently partition code into easily loadable modules

My current issue: I am facing a challenge with splitting my vue.js code into chunks. Despite trying multiple examples from tutorials, I am unable to successfully separate the components and load them only when necessary. Whenever I attempt to divide the c ...

Vue.js component still not transitioning out despite using mode="out-in"

As I navigate my way through learning about vue.js, one issue that has been puzzling me is how to make routed pages fade in and out when a user switches to a new page. Despite thinking it would be a simple task with vue, I have been struggling quite a bit ...

Transform the look of an inactive hyperlink

Can the visual style of an HTML link be modified when it is disabled? For instance, by implementing something like this: a.disabled { color:#050; } <a class="disabled" disabled="disabled" href="#">Testing</a> The code snippet above appears ...

Determine whether a subdomain is present within an ajax file in php

Looking for assistance with checking the existence of a 'Subdomain' in a file called '\example\sites'. Here's the code: $form = array() ; $form['name'] = "install"; $form['action'] = "?step=2"; $for ...

Tips for adjusting the placement of enlarged images within colorbox

I recently discovered colorbox and decided to use it as my lightbox solution. However, I encountered a challenge with positioning the background (#cboxOverlay). I wanted to move it 120px to the left so that some content from the original page would still ...

uniformly distribute the list items on the horizontal navigation bar

Does anyone know how to properly space out a ul in a navigation bar, with 5px padding on the right and left and the text evenly spaced in between? body { background: #ffffff; text-align: center; font-family: helvetica, arial, san ...

Navigating programmatically to another page in Next.js can be easily achieved by utilizing the useRouter hook

Following a post request to an external API, my goal is to navigate back to the homepage. While I am familiar with React, this is my first experience using Next.js. Here's the snippet of code: export default function New({genres}) { const createMovie ...

What is the best way to populate a dropdown menu by matching keys from an array within an ng-repeat

My JSON structure looks like this: 101 : "List": [ { "Name": "Pink" }, { "Name": "Black" } ] 102 : "List": [ { "Name": "Red" }, { "Name": "Yellow" } ] $sco ...

Click to expand for answers to commonly asked questions

Having trouble setting up a FAQs page on my blog and can't seem to get the code right. Check out what I'm trying to do here: http://jsfiddle.net/qwL33/ Everything seems fine but when I click on the first question, both questions open up. Can som ...

Darkening the background of HTML and CSS text to black

I'm having trouble removing the black background from the navigation. It doesn't appear to be styled in black when I inspect each element individually. Here is an image showing the issue: https://i.stack.imgur.com/gvbn8.png @charset "UTF-8"; ...

A webpage specified with 'charset=iso-8859-1' accompanied by <!DOCTYPE HTML> is triggering a cautionary alert

After running the W3C validator on an HTML document, I discovered that using the following meta tag: <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> in conjunction with: <!DOCTYPE HTML> results in ...

JQuery ID Media Queries: Enhancing responsive design with targeted

Is it possible to integrate a media query into the selection of an ID using JQuery? For example: $('#idname') $('@media (max-width: 767px) { #idname }') In essence, can you target the #idname with that specified media query in JQuery ...