Prevent event propagation in jQuery by using .stopPropagation() when hovering over a

When trying to implement event.stopPropagation() in a specific scenario, I encountered an issue with a blinking background image on my submenu. To address this, I added a pseudo-element (background:green) to the parent element by toggling a new class using jQuery. While this solution achieved the desired outcome, it resulted in the background image flickering.

Check out the jsfiddle here

View live site for reference (issue present in the top menu)

HTML:
<ul class="top-menu">
 <li>
  <a href="#">link 1</a>
  <div class="submenu">
   <ul>
    <li><a href="#">sublink 1</a></li>
    <li><a href="#">sublink 2</a></li>
    <li><a href="#">sublink 3</a></li>
    <li><a href="#">sublink 4</a></li>
    <li><a href="#">sublink 5</a></li>
   </ul>
  </div>
 </li>
 <li><a href="#">link 2</a></li>
 <li><a href="#">link 3</a></li>
</ul>

Javascript/jQuery:

            $(".submenu a").mouseover(function(e){
              $(".submenu").addClass("myclass");
            }).mouseout(function(e){
              var cover = $(".submenu");
              cover.data('timer', setTimeout(function(){
                    cover.removeClass("myclass');
                }, 2000)
              );
              e.stopPropagation();
            });

CSS:

*{
  box-sizing:border-box;
}
ul.top-menu {
  display:flex;
  list-style:none;
  text-transform:uppercase;
  width:100%;
  justify-content:center;
  background:white;
  position:relative;
}
ul.top-menu li a {
  color:black;
  padding:10px;
  text-decoration:none;
  display:block;
}
.submenu {
  position:absolute;
  background:red url("http://www.metalclays.com/content/images/thumbs/0002871_texture-tile-fireworks_100.jpeg");
  background-position:right top;
  background-size:200px auto;
  background-repeat:no-repeat;
  width:100%;
  top:100%;
  left:0;
  z-index:0;
}
.submenu:after {
  content:"";
  background:green;
  width:100%;
  height:100%;
  position:absolute;
  top:0;
  left:0;
  opacity:0;
  z-index:-1;
}  
.submenu.myclass:after {
  opacity:1;
}
.submenu ul {
  list-style:none;
}
.submenu a {
  color:white;
  display:block;
}

Answer №1

Did you give this a shot?

$(".submenu a").mouseover(function(e){
  $(".submenu").addClass("myclass");
}).mouseout(function(e){
  e.preventDefault();
  $(".submenu").removeClass("myclass");
});

Answer №2

When you modify the class on the parent element, it causes the background image to flash.

This issue arises because whenever you hover over the element, the class keeps getting added repeatedly. To fix this problem, update your code like so:

$(".submenu a").mouseover(function(e){
    if ($(".submenu.myclass").length == 0) {
        $(".submenu").addClass("myclass");
    }
})

You can view the revised version on this updated fiddle.

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

Send a form to two different servers

I am looking for a solution to submit forms to two different servers simultaneously. Here is the situation and challenge I am facing. Currently, I have an iframe embedded on Mechanical Turk which contains a form. When a worker submits this form, there are ...

jQuery Autocomplete - struggling to pinpoint the exact location where the width of the suggestions div is being defined

I have successfully implemented jQuery Autocomplete, but I am facing an issue with adjusting the width. Currently, it is set to 268px in Firebug, however, I would like it to be 520px. After checking the stylesheet, I couldn't locate where the width o ...

Representation of a family tree in CSS showcasing multiple sub-parents (both many to one and one to many relationships)

I've come across various family tree presentations. I'm curious if it's possible to display a one-to-many and then many-to-one structure? Currently, the flow is linear stop after stop, but I'd like to incorporate multiple steps that con ...

Trouble with Add To Cart feature in React app due to issues with Context API

I have been following a tutorial located here. I followed the steps exactly and even checked the code on the related github repository, which matches. However, when I try to add a product to the cart by clicking the button, the state does not update. In Re ...

Ensure that the image inside a resizable container maintains the correct aspect ratio

I often encounter a situation where I need to showcase a series of thumbnails/images that adhere to a specific aspect ratio within a flexible container. My current approach involves using a transparent, relatively positioned image to enforce the correct as ...

Instructions for removing a class using the onclick event in JavaScript

Is there a way to make it so that pressing a button will display a specific class, and if another button is pressed, the previous class is removed and a new one is shown? Thank you for your assistance. function myFunction() { document.getElementById ...

Kik Card - Using Synchronous XMLHttpRequest within the Kik.js Script

Getting ready to create a mobile web app powered by Kik! First step, insert the Kik.js script at the bottom of your HTML page... <!-- add this script to your webpage --> <script src="http://cdn.kik.com/kik/2.3.6/kik.js"></script> Excel ...

JavaFX WebEngine pauses until ajax is finished

Currently, I am working on a JavaFX data mining application that heavily relies on WebView and WebEngine. The entire mining process involves two main steps. Firstly, the user navigates to a specific website using the UI in WebView to configure the search f ...

Does Vue.js interfere with classList.remove functionality?

When working with Vue.js, I encountered an issue where elements would briefly flash curly braces to the user before being hidden. To combat this problem, I implemented the following solution: HTML: <div class="main hide-me" id="my-vue-element"> ...

What could be causing the template UI to not display the Vue data?

As someone new to Vue, I have defined my Vue code in the following way: import Vue from "vue"; export default Vue.extend({ data: () => { message: "show message"; }, }); <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js ...

Finding MongoDB data using an Express route and displaying it in a Jade template

Is there a way to retrieve data from MongoDB using an express route and display it in a jade template? Below is the code snippet of my express route (express version 2.5.8): app.get('/showData',function(req,res){ db.collection('comme ...

What should I do to resolve the issue of the function if ($(window).width() < 768) {} not functioning properly upon resizing the browser?

I am working on a functionality where the navigation bar items will toggle hidden or shown only when the browser width is less than 768px and an element with the class "navlogo" is clicked. I have included my code below for reference. if ($(window).width( ...

Navigating Angular.js: finding my way to the endpoint paths

Despite my best efforts and extensive research, I find myself in need of assistance! I have a web application that utilizes node and express on the server side, with Angular on the client side. My issue lies with angular routing. IMPORTANT DETAILS My cur ...

The JavaScript syntax dollar sign

I am currently studying a JavaScript source code and it's my first time writing JavaScript. I find some of the syntax confusing. <script id="source" language="javascript" type="text/javascript"> $(function () { window.onload=function() ...

Utilizing the map() function to parse a Json object

Looking for guidance with working with a JSON object structured like this: {"Title":"asb","Date":"2019","Other":"not important"} How can I correctly read this object and render it in <ul><li> format? Please Note: I have attempted to assign th ...

Utilizing variables in Angular service to make API calls

Currently, I am working on accessing the Google Books API. Initially, I was able to directly access it in my controller but now I want to follow best practices by moving the business logic into a directive. HTML <form ng-submit="search(data)"> < ...

Preventing memory leaks by harnessing the power of Node Streams and promises

I am trying to wrap node streams in an async function, but I'm concerned about potential memory leaks in the following code. Will readStream and result be properly garbage collected after the promise is resolved or rejected? If not, what steps can I t ...

The conventional method for including React import statements

I'm curious if there is a standard convention for writing import statements in React. For instance, I currently have the following: import React, { useState, FormEvent } from 'react'; import Avatar from '@material-ui/core/Avatar'; ...

two interlinked checkboxes

I am currently working on a project that involves two checkboxes. When each checkbox is clicked individually, they perform their respective tasks. However, if both checkboxes are clicked at the same time, an additional task needs to be performed. I am enco ...

Provide Arguments to a Function in Express JS

How's everything going? I'm curious to find out the best way, and if it's possible to send a specific parameter to an express function in NodeJS. I want to pass the string ('admin') or any other string that I choose to the 'R ...