Stop the bubbling effect of :hover

How can the hover effect be prevented for the parent element when hovering over its children?

Please take a look at the following code snippet:

const parent = document.getElementById('parent')
parent.onmouseover = function testAlert(e) {
  /* alert('parent') */
}
const childRight = document.getElementById('child-right')
childRight.onmouseover = function f(e) {
  e.stopPropagation()
  /* alert('child-right') */
}
const childLeft = document.getElementById('child-left')
childLeft.onmouseenter = function f(e) {
  e.stopPropagation()
  /* alert('child-right') */
}
#parent {
  background: green;
  width: 100px;
  height: 100px;
  position: relative;
  margin: 0 auto;
}

#parent:hover {
  background: rgba(0, 0, 0, 0.8);
}

#child-left {
  background: red;
  width: 50px;
  height: 50px;
  position: absolute;
  top: 0;
  left: -50px;
}

#child-right {
  background: red;
  width: 50px;
  height: 50px;
  position: absolute;
  top: 50px;
  left: 100px;
}
<div id="parent">
  <div id="child-left"></div>
  <div id="child-right"></div>
</div>

https://jsfiddle.net/3tjcsyov/48/

Upon examining the code, it is evident that hovering over the red rectangles also triggers the hover effect on the green rectangle due to CSS behavior. Although using stopPropagation prevents JavaScript handlers from executing on the parent element, the CSS behavior remains unaffected.

Answer №1

To achieve this effect without using JavaScript, you can simply set the children's pointer-events to none.

#container {
  background: green;
  width: 100px;
  height: 100px;
  position: relative;
  margin: 0 auto;
}

#container:hover {
  background: rgba(0, 0, 0, 0.8);
}

#child-left {
  background: red;
  width: 50px;
  height: 50px;
  position: absolute;
  top: 0;
  left: -50px;
}

#child-right {
  background: red;
  width: 50px;
  height: 50px;
  position: absolute;
  top: 50px;
  left: 100px;
}

#child-left,
#child-right {
  pointer-events: none;
}
<div id="container">
  <div id="child-left"></div>
  <div id="child-right"></div>
</div>

https://jsfiddle.net/bepLktoj/

Answer №2

Implementing pointer-events:none with the selectors #child-left and #child-right can effectively control hover styling in a scenario where you only want the hover effect to occur when the #parent is hovered over, without affecting the children elements. To achieve this, you simply need to include the following code in your style sheet:

#child-left,
#child-right {
  pointer-events: none;
}

For a more complex situation where individual hover styles are required for each element within the parent-child relationship, script intervention becomes necessary since the styling hierarchy goes from parent to child rather than vice versa.

An approach to address this complexity involves introducing a custom .hover modifier class that emulates the behavior of the standard :hover selector. This .hover class would define specific styling attributes for targeted elements, while a script would toggle the class based on mouse interactions.

A basic script can be utilized to add or remove the hover class on the event#target element provided by the Event object during mouseover and mouseout events:

const parent = document.getElementById('parent');

/*
Add mouse over and mouse out event listeners to 
add/remove hover class from the event's target element
*/

parent.addEventListener('mouseover', (event) => {
  /* 
  event.target is the actual element that triggers this 
  mouse event (ie the #parent or either of the children)
  */
  event.target.classList.add('hover');
})

parent.addEventListener('mouseout', (event) => {
  /* 
  event.target is the actual element that triggers this 
  mouse event (ie the #parent or either of the children)
  */    
  event.target.classList.remove('hover');
})
#parent {
  background: green;
  width: 100px;
  height: 100px;
  position: relative;
  margin: 0 auto;
}

#child-right {
  background: red;
  width: 50px;
  height: 50px;
  position: absolute;
  top: 50px;
  left: 100px;
}

#child-left {
  background: red;
  width: 50px;
  height: 50px;
  position: absolute;
  top: 0;
  left: -50px;  
}

/*
Introduce hover modified class, which is toggled
via javascript and substitutes the native CSS 
:hover selector. I've explicity defined a selector 
for each element however via SCSS this can be 
simplified */
#parent.hover,
#child-left.hover,
#child-right.hover {
  background: rgba(0,0,0,0.8);
}
<div id="parent">
  <div id="child-left"></div>
  <div id="child-right"></div>
</div>

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 it possible to declare variables using the "this" keyword?

Consider the scenario where this.x=5 is declared and assess the accessibility of all relevant places. <script> $(document).ready(function(){ $("button").click(function(){ this.x=!this.x; $("#div1").fadeTo(400,this.x ? 0.4 : 1); }); }); & ...

UI-Router: What is the best way to access a page within my project without adding it as a State?

Currently in the process of learning Angular and UI-Router. Initially, I followed the advice of many and chose to utilize UI-Router. In my original setup, the login page was included in all States. However, I decided it would be best to keep it as a separ ...

Is there a way to upload multiple files using expressjs?

I'm looking for a way to efficiently send multiple files, including an entire directory, so that I can access them in another JavaScript file called from an HTML file. const app = require("express")(); const http = require("http"). ...

Utilizing Data From External Sources in a React Application

I have encountered an issue with displaying data from another page in a reusable table I created using React. Specifically, I am having trouble getting the value to be shown in <TableCell> Please check out this code sandbox link for reference ACCES ...

Releasing the mouse button after dragging successfully without the use of any libraries

I have implemented a pure CSS snap scroll feature and now I need to determine the position of an element in relation to the viewport once the user stops dragging. However, I prefer not to rely on any complex libraries as I do not require any actual movemen ...

Vue-Firebase: A guide to linking multiple Firebase services in a single app

I am facing an issue with connecting to two firebases within the same project. In my project, I have two javascript files that connect to each firebase separately, which seems fine. Here is how I import them: import db from '../FireBase' i ...

Utilize $.ajax to gracefully wait for completion without causing the UI to freeze

Consider a scenario where there is a JavaScript function that returns a boolean value: function UpdateUserInSession(target, user) { var data = { "jsonUser": JSON.stringify(user) }; $.ajax({ type: "POST", url: target, data: ...

I'm not sure if I'm doing this right, the image seems to be overlapping the border

Just dipping my toes into the world of HTML/CSS, so feel free to point out any major errors in my code. The issue I'm facing is illustrated in this image (Apologies for the black boxes covering up some content; focus is on the top image). Check out ...

What is the best way to arrange form inputs in a single row?

My form consists of three input boxes. While the first two inputs are single line, the third is a description field with 10 rows set as default. However, for some reason, this third box is not aligned properly with the other two. Please refer to the screen ...

What are the reasons for the various methods available for importing my JS code?

Here is the structure of my folders: --public ----frontend.js --views ----fontend.ejs The frontend.js file is located inside the public folder, while the frontend.ejs file is in the views folder. In my HTML / EJS file, I included the JavaScript (fronten ...

What is the process for loading a font file in Vue.js and webpack?

I've done a lot of research, but I couldn't find any links that show me exactly how to add fonts in VueJS. This is the method I'm using to import the font in my LESS file: @font-face { font-family: "Questrial"; src: url("../../fonts/Que ...

issue with implementing the chart.js npm package

Just recently, I added chart.js to my project using npm. My goal is to utilize the package for creating graphs. npm install chart.js --save After the installation, I attempted to import the module with: import chart from 'Chartjs'; However, t ...

Lifting Formik's "dirty" value/state to the parent component: A step-by-step guide

Parent Component const Mother = () => { const [dusty, setDusty] = useState(false) return ( <ChildComponent setDusty={setDusty} /> ) } Child.js ... <Formik initialValues={initialValues} onSubmit={onSubmitHandler} validationSchema={sch ...

CSS/jQuery animation alignment problem

Exploring an animation using CSS transitions and jQuery has been my recent project. The concept involves presenting the user with clickable divs to load a new page. When a div is clicked, it expands to cover the entire screen and transition to the next pag ...

Steps for creating a table with a filter similar to the one shown in the image below

https://i.sstatic.net/zR2UU.png I am unsure how to create two sub-blocks within the Business A Chaud column and Potential Business Column. Thank you! I managed to create a table with input, but I'm struggling to replicate the PUSH & CtoC Column for ...

The Three.js camera imported from Collada is unable to properly focus on an object within the scene

Having some trouble grasping the concept of Collada Animation in Three.js! I have an animation with a moving camera in 3Dsmax, and exported the scene into Collada. loader.load( ColladaName, function ( collada ) { model = collada.scene; model.upda ...

The Process of Sending Values from app.js to a Vue File in Vue.js

My app.js is currently receiving a value called gtotal. I am trying to pass this value to the orderForm.vue file but am facing some difficulties in achieving this. require('./bootstrap'); window.Vue = require('vue'); window.EventBus ...

Curved edges on a text box featuring a scroll bar

I'm facing an issue with my website where I have a large amount of text in an html textarea that requires a scroll bar. The problem is, I'd like to add rounded corners to the textarea, but it doesn't look good with the scroll bar. Below is ...

Mutating properties in VueJs

When I attempted to move a section for filtering from the parent component to a child component, I encountered this error message: "Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a ...

Determining the Next Available Date from JSON Data

I have a task of using a JSON response from the Eventbrite API to showcase the upcoming event tour date. The goal is to automatically calculate this date based on the current time, identifying the next event after the current moment. Below is the JSON res ...