Hovering over and leaving a child submenu with a mouse

Here is a menu that I created using ul element:

<ul class="offerings">
   <li><a>NO SubMenu</a></li>
   <li><a>With SubMenu</a>
      <ul id="submenu">
        <li><a href="">SubMenu 1</a></li>
        <li><a href="">SubMenu 2</a></li>
      </ul>
   </li>

I want the submenu (id=submenu) to display when hovering over <a>With SubMenu</a>, and hide when moving the mouse away from it.

While achieving hover effect on mouseenter is simple, handling mouseleave event on

<li><a>With SubMenu</a>
poses a challenge.

The issue at hand is:

If the submenu is open and the mouse enters the box of the submenu, the mouseout event occurs on <a>With SubMenu</a>, causing the submenu to disappear. How can this scenario be addressed?

One approach could be to consider mouse coordinates and only execute the mouseleave function if necessary.

https://jsfiddle.net/vkfc9jwc/6/

Answer №1

There's a way to achieve the same effect using CSS as well:

ul ul{display:none;} /*hides the sub-list*/

li:hover ul{display:block;} /*displays the ul on li hover*/
<ul class="offerings">
  <li><a>NO SubMenu</a></li>
  <li><a>With SubMenu</a>
    <ul id="submenu">
      <li><a href="">SubMenu 1</a></li>
      <li><a href="">SubMenu 2</a></li>
    </ul>
  </li>
</ul>

Answer №2

To achieve this using jQuery, simply bind the events to the li element instead of the a tag. However, it is advisable to take into account Jai's answer.

$('.offerings').find('>li').on('mouseover',function(e){
    $("#eventFired").text('Fired XXX');
});

$('.offerings').find('>li').on('mouseout',function(e){
    $("#eventFired").text('mouseout Fired on A');
});

The corresponding fiddle can be viewed here: https://jsfiddle.net/vkfc9jwc/7/

Answer №3

Instead of using scripts, you can achieve the same effect by utilizing the :hover rule.

.offerings ul {
  display: none;
}
.offerings li:hover ul {
  display: block;
}
<ul class="offerings">
  <li><a>NO SubMenu</a>
  </li>
  <li><a>With SubMenu</a>
    <ul id="submenu">
      <li><a href="">SubMenu 1</a>
      </li>
      <li><a href="">SubMenu 2</a>
      </li>
    </ul>
  </li>
</ul>
<label id="eventFired">Class</label>


If you prefer to use a script, you can implement the functionality with the mouseenter and mouseleave events instead of mouseover and mouseout.

You can utilize the .hover() function which combines both mouseenter and mouseleave handlers:

$('.offerings li:has(ul)').hover(function(e) {
  $(this).children('ul').toggle(e.type == 'mouseenter');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="offerings">
  <li><a>NO SubMenu</a>
  </li>
  <li><a>With SubMenu</a>
    <ul id="submenu">
      <li><a href="">SubMenu 1</a>
      </li>
      <li><a href="">SubMenu 2</a>
      </li>
    </ul>
  </li>
</ul>
<label id="eventFired">Class</label>

Answer №4

Have you experimented with the JQuery Hover method yet?

$( "#submenu li" ).hover(
  function() {
    $("#eventFired").text('Sub Menu LI HOVER');
  }, function() {
    $("#eventFired").text('Sub Menu LI UN-HOVER');
  }
);

$( "#submenu" ).hover(
  function() {
    $("#eventFired").text('Sub Menu HOVER');
  }, function() {
    $("#eventFired").text('Sub Menu UN-HOVER');
  }
);

Answer №5

Here is a suggestion for achieving the desired result:

$('.offerings').find('>li').on('mouseover',function(e){
  $("#submenu").css('display', "block");
});

$('.offerings').find('>li').on('mouseout',function(e){
  $("#submenu").css('display', "none");
});

Answer №6

Another approach you could consider is using the following code snippet, although as @Jai mentioned earlier, achieving this effect with css is also possible.

    $('.items').find('> div > a').on('click',function(e){
    $("#buttonClicked").text('Button Clicked');
});

$('.items').find('> div > ul > li > a').on('dblclick',function(e){
    $("#eventFired").text('Double click event on A');
});

Answer №7

If you're looking to add interactive hover effects to your website, I suggest using the hover() function from the jQuery library. First, you'll need to include the jQuery library in your project by adding it to the <head> section of your HTML document. This step is crucial for the script I'm about to share with you to work properly. Once the jQuery library is loaded, you can proceed to write the actual script using jQuery.

The hover() function consists of two parts: one that triggers on mouse-enter event and another that triggers on mouse-out event. You can see this functionality in action in this JSFiddle: https://jsfiddle.net/h9ocupsh/1/

To implement the hover function, your script will look something like this:

$(document).ready(function(){
    $(".hoverable").hover(function(){
        $("#submenu").show();
    }, function(){
        $("#submenu").hide();
    });
});

Make sure to identify the <li> element that triggers the hover function by using a specific class like "hoverable". You can customize this by changing the class or id in the script accordingly. For example, if you want to use an id "hover" instead of a class, you would modify it to: $("#hover").

Don't forget to position the submenu according to your preferences if needed.

I've provided a link to the jQuery library for your convenience - simply include it in your HTML file before the jQuery scripts.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>

Optional: You can adjust the timing of the show() and hide() functions to control the speed of displaying or hiding elements. Simply add a value in milliseconds, such as show(400).

Additionally, ensure that the CSS display property for your <ul id="submenu"> is set to "none" initially. Finally, place the provided script after including the jQuery library in the <head> section of your document for everything to work smoothly.

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

Is there a way in Angular Material to consistently display both the step values and a personalized description for each step?

Is there a way to display both numerical step values and corresponding custom text in Angular Material? I prefer having the number at the top and the descriptive text at the bottom. Check out this image for reference: https://i.stack.imgur.com/LGMIO.png ...

Is there a way to handle error messages in JSON format when working with PHP?

**var ajaxUrl='admin/includes/validation.php?ref=enquiry&name='+$("#name").val() + '&email1='+$("#email1").val() + '&phone='+$("#phone").val()/*+ '&check='+a*/; $.ajax({ type: "POST", u ...

Choose Selectize.js to auto-populate inputs

I am currently using selectize.js for my project: $("#abc").selectize({ valueField: 'name', labelField: 'name', searchField: ['name'], plugins: ['remove_button'], createOnBlur: true, ...

React Native Issue: The mysterious disappearance of the 'navigation.push' object

I am trying to navigate to List.js after clicking a button in the MainMenu.js file, but I keep encountering this error: TypeError: undefined is not an object (evaluating 'navigation.push') This snippet is from my App.js file import { StatusBar ...

Is there a way to retrieve the real-world position in threeJS without having a mesh directly under

code.js // ... this.width = 2000 this.height = 2000 // ... this.camera = new THREE.OrthographicCamera(this.width / -2, this.width / 2, this.height / 2, this.height / -2, 1, 1000 ); this.camera.position.z = 100; this.camera.position.x = 600; this.camera.p ...

Manipulate SVG elements with JavaScript to embed a PNG image into the SVG file

Is it possible to edit an SVG, such as changing the fill color and other SVG methods? I am also looking to insert an SVG/PNG within another SVG at a specific path or group. Can someone provide guidance on how to achieve this? ...

Stop angular material css styles from affecting neighboring components

Currently, I have overridden the angular material style in my global SCSS style as follows: .mat-form-field-infix{ padding: 0.5em 0 0.5em 0 !important; } However, I now need to apply a different padding to the same element in my component for addition ...

Retrieve data from the database and insert it into a newly created row dynamically

I am a beginner in the world of PHP programming. Currently, I am working on creating a billing system program. I have successfully created a table and added rows to it dynamically. Now, my next challenge is to add values from a database to these dynamicall ...

retrieving the AJAX response from a PHP CodeIgniter API

My issue is that I am currently working on developing a Codeigniter API. This framework is new to me, and it's my first time building an API. To get started, I followed a simple tutorial to create a basic API with the following controller: /** * @rou ...

The alias for the last item in a nested ng-repeat loop will consistently evaluate to true

Within my code, I am utilizing two nested ng-repeat functions and I am looking to change the $last variable to something different for each level - let's say outerLast and innerLast. I attempted to achieve this by using ng-init="outerLast= $last" and ...

Creating HTML forms allows for images to be used as checkboxes

I'm attempting to convert an HTML forms checkbox into a clickable image that changes its appearance when clicked. Additionally, I need it to be capable of storing one or two variables (specifically for generating them with row and column values) and f ...

Guide on how to use Vue's watch feature to monitor a particular property within an array

I am interested in observing the "clientFilter" within an array TableProduit: [ { nr_commande: 0, date_creation: "", id_delegue: "1", clientFilter: "" } ], ...

Creating Dynamic Dropdowns with Bootstrap 5 Animation

I've been trying to add animation to a right-aligned Bootstrap dropdown using CSS, but I'm having trouble getting it to work. I attempted setting the transition property to target the element's width, but it doesn't seem to be effective ...

Protecting against Cross-Site Request Forgery (CSRF) and Cross-S

When it comes to my application, I require clients to generate a unique token for themselves before making any requests to access server resources. However, this method alone does not fully protect against CSRF attacks. So, what are the most effective str ...

Searching through Mongoose using various fields, some of which are optional

Recently, I've delved into the world of mongoose and am currently working on an app to enhance my learning. My project involves an Artist Schema and a search form with multiple optional fields. For example, users can input a name, minimum age, and sea ...

The functionality of the localStorage HTML5 feature is experiencing issues within the WebView on Samsung Android devices

I am currently facing an issue with my HTML5 application which I am wrapping with a WebView. In order to store and retrieve user input values between pages, I have been utilizing the localStorage feature in HTML5. Interestingly, this feature functions per ...

Preventing Other Devices from Establishing Connections

My goal is to restrict access to my website so that only mobile devices can enter. I have the ability to utilize node.js, HTML, and PHP in my website development. How can I go about blocking connections from other devices? ...

Struggling to remove an image while using the onmouseover event with a button?

I am encountering an issue with hiding an image using the onmouseover event not applied directly to it, but rather to a button element. The desired functionality is for the image to appear when the mouse hovers over and disappear when it moves away. Here&a ...

The 'in' operator cannot be used to look for 'size' within

I came across an informative answer Following the advice in the answer, I implemented the following code: function fetchCountryInfo() { $.ajax({ url: "https://en.wikipedia.org/w/api.php?action=parse&disablelimitreport=true&format=json&p ...

Choose a specific "field" from a Firebase array

I am currently working on a project using AngularJS and Firebase, and everything seems to be functioning well. https://i.sstatic.net/ojy2Z.png However, I am facing a challenge of extracting only temperature values into one array and humidity values into ...