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

Issue with Jquery's dotdotdot.js plugin when handling text containing HTML components is causing malfunction

For my current project, I have incorporated dotdotdot.js to handle text truncation. However, after integrating a rich-text editor (tinymce), some HTML elements like p, a, b, i, etc., have been added to the text. Unfortunately, dotdotdot is now not behaving ...

When a React page is re-rendered using useEffect, it automatically scrolls back to the

Every time I utilize the <Tabs> component, the onChange method triggers the handleTabChange function. This leads to the component being called again and after repainting, the useEffect is triggered causing the page to scroll back to the top. How can ...

What is the process of overriding methods in a function-based component in React?

Overriding in a parent component works when it is a class-based component // Parent Button Class class Button extends React.Component { createLabel = () => { return <span>{this.props.label}</span>; }; render() { return <butt ...

Integrating additional youngsters into the HTML DOM using Angular.js

I am working with a block of HTML that looks like this: <div id="parent"> <div id="child_1"></div> <div id="child_2"></div> <div id="child_3"></div> <div id="child_4"></div> </div> ...

Attempting to execute a synchronous delete operation in Angular 6 upon the browser closing event, specifically the beforeunload or unload event

Is there a way to update a flag in the database using a service call (Delete method) when the user closes the browser? I have tried detecting browser close actions using the onbeforeunload and onunload events, but asynchronous calls do not consistently wor ...

Align content vertically within a div container

I have encountered an issue where I am trying to center vertically the content within a div. Here is an example of the structure: <div class="container-fluid"> <div class="row restaurant"> <div class="col-md-6"> & ...

Incorporate npm libraries into vanilla JavaScript for HTML pages

Attempting to incorporate an npm package into plain JS/HTML served using Python and Flask. <script type="module"> import { configureChains, createClient } from "./node_modules/@wagmi/core"; import { bsc } from "./nod ...

Restrict the quantity of recommendations provided by the AutoComplete feature

After exploring the autocomplete API from https://material-ui.com/api/autocomplete/, I am unable to figure out a way, given my basic understanding of javascript, to restrict the display of a specific number of options beneath the TextField. I am working o ...

Exporting modules from Node.js using Express framework is a common

Encountering an issue with this error message Error: app.get is not a function This section shows my configuration in config/express.js var express = require('express'); module.exports = function(){ var app = express(); app.set(&apo ...

What is the best way to integrate a Vue component into a Knockout application?

My webpage is filled with knockout code, but I'm hoping to integrate a Vue.js component for a specific section. I attempted using controlsDescendantBindings on a surrounding tag for the Vue component, and it seems to be partially functional (I tried ...

There was a lack of dynamic content on the webpage when using the view/template engine (Handlebars)

I'm currently using the Handlebars template engine in my project. Despite not encountering any errors in the console, I'm facing an issue with displaying dynamic content in the index.hbs file that is rendered from app.js. app.js const express = ...

Rails Unobtrusive JavaScript (UJS) does not seem to be connecting the data-remote

Version of Rails: 3.2.1 Version of Ruby: 1.9.3p125 Browser Used: Chrome 18.0.1025.162 Developers Operating System: Mac OS/X Lion Server's Operating System: CentOS 5 I am attempting to utilize :remote in my link_to call in order to request HTML co ...

In the game of rock paper scissors, the icons become unclickable once you achieve a score of 5

I have created a Rock Paper Scissors game where the score resets if either the user or computer reaches 5 points, but I want to prevent any further play after hitting 5. Currently, the game displays a message and reloads after 5 seconds, during which tim ...

Change the border color of radio buttons when clicked

When one of the radio buttons is clicked, it should give an outer border with color. When the other radio button is clicked, it should give an inner border that surrounds the image. <!DOCTYPE html> <html> <head> ...

The Mantine date picker is causing an error stating that objects are not valid as a React child

I'm currently experimenting with utilizing Mantine Date in NextJS. The goal is to have the selected date displayed in the HTML text heading when a user clicks on it. For instance, if a user selects January 1st, 2023, the text should show like this: Da ...

Guide on adjusting the resolution/density of images in JPEG/PNG using JavaScript

I am looking for a way to adjust the resolution/density of JPG/PNG images using JavaScript. The purpose of this adjustment is to provide accurate metadata on the number of pixels per inch (DPI/PPI) to be used for printing by a third-party API. Is there a ...

A method for merging the values of three text fields and submitting them to a hidden text field

<label class="textRight label95 select205">Cost Center: </label> <input type="hidden" name="label_0" value="Cost Center" /> <input type="text" name="value_0" class="input64 inputTxtGray" value="" maxlength="10" /> <input type=" ...

Limiting zero is ineffective when it comes to pop-up issues

Hey there, I'm looking to prevent users from inputting zero and dot in a specific field, which is currently working fine. However, when the field is within a pop-up, the code below doesn't seem to work. <script> $('#name').keyp ...

The antithesis of jQuery's .parents() selector

I am currently developing a userscript for a webpage with an old-fashioned design consisting mainly of tables. My goal is to access a long table of fields so that they can be filled in automatically by the script. To simplify, the structure is as follows: ...

Attempt to retrieve JSON-formatted data from a repository on Git

As a novice, I am delving into the world of ajax and experimenting with json files. Utilizing JSON formatted data is something I am keen on mastering. However, my request seems to be yielding an empty outcome. An Update: Below is the piece of code I am wor ...