Elements overlapped with varying opacities and responsive to mouse hovering

In this Q/A session, we will explore a JS solution for managing the opacity of overlapping elements consistently during hover.

Objective

Our goal is to create two transparent and overlapping elements, similar to the red boxes showcased below. These elements should allow the background to show through.

https://i.sstatic.net/hak6k.png

Upon hovering over either element, it should transition to an opaque state as demonstrated below.

https://i.sstatic.net/B6GoB.png

Answer №1

One efficient solution using only CSS is as follows:

body {
  background-image: linear-gradient(45deg, transparent 50%, #aaa 75%);
  background-size: 20px 20px;
}

#a {
  position: absolute;
  width: 150px;
  height: 150px;
  top: 50px;
  left: 50px;
  background: rgba(255, 0, 0, 1);
}

#b {
  position: absolute;
  width: 150px;
  height: 150px;
  top: 125px;
  left: 125px;
  background: rgba(255, 0, 0, 1);
}

#wrapper {
  opacity: 0.5;
}

/* You can use selectors instead of changing classes, like this:*/

#wrapper:hover #a:hover,
#wrapper:hover #b:hover {
  opacity: 1;
  z-index: 10;
}

#wrapper:hover {
  opacity: 1;
}

#wrapper:hover #b,
#wrapper:hover #a {
  opacity: 0.5;
  z-index: -1;
}
<div id=wrapper>
  <div id="a">
  </div>
  <div id="b">
  </div>
</div>

Answer №2

Utilizing absolute positioning for elements, I have successfully implemented a feature where each element can be moved on top of the wrapper upon mouse enter and back to its original position on mouse leave, using pure JavaScript.

The example now consists of 3 elements, highlighting any artifacts in the code and adding borders to visualize the overlapping effect.

View CODEPEN

Here is the HTML structure:

<div id=top>
  <div id=wrapper>
    <div class="first" onMouseEnter="hover3b(event)" onMouseLeave="hover3e(event)"></div>
    <div class="second" onMouseEnter="hover3b(event)" onMouseLeave="hover3e(event)"></div>
    <div class="third" onMouseEnter="hover3b(event)" onMouseLeave="hover3e(event)"></div>
  </div>
</div>

The corresponding CSS styling:

body {
  background-image: linear-gradient(45deg, transparent 50%, #aaa 75%);
  background-size: 20px 20px;
}

.first, .second, .third {
  width: 100px;
  height: 100px;
  background-color: red;
  position: absolute;
  border: 3px solid black;
}

#wrapper {
  width: 200px;
  height: 200px;
  background-color: yellow;
  border: 3px solid green;
  opacity: 0.6;
}

.first { left: 0px; top: 0px; }
.second { left: 80px; top: 80px; }
.third { left: 160px; top: 160px; }

Lastly, the JavaScript implementation:

var from = null; // remember where to put back the element
function hover3b(e) {
  var t = e.target;
  from = t.nextElementSibling;
  if (!from)
    from = null;
  document.getElementById("top").appendChild(t);
}
function hover3e(e) {
  document.getElementById("wrapper").insertBefore(e.target, from);
}

Answer №3

Resolution

In order to address the issue, the solution involves the creation of two elements and potentially a wrapper for them.

<div class="container">
  <div class="element-one"></div>
  <div class="element-two"></div>
</div>

Following that, the elements are styled to align with the design specifications.

.element-one,
.element-two {
  width: 100px;
  height: 100px;
  background-color: red;
  opacity: 0.6;
}

Furthermore, code snippets are provided for managing the overlap.

.element-two {
  margin-left: 50px;
  margin-top: -50px;
}

One limitation of this method is the inconsistency in opacity within the overlapped area, resulting in a darker tint.

https://i.sstatic.net/JNspz.png

It is crucial to note that this issue is not browser-related, and an explanation for this behavior is available here.


The Optimal Approach

A more effective strategy for handling this scenario is to refrain from making the child elements transparent and instead adjusting the 'opacity' at the parent level. During hover events, the opacity levels can be toggled between the parent and children elements using JavaScript.

$(".element-one, .element-two").hover(function() {
  $(".container, .element-one, .element-two").not(this).toggleClass("add-opacity");
});

Moreover, flickering when hovering over the overlapped area can be prevented by setting the z-index for the hovered element.

.element-one:hover,
.element-two:hover {
  z-index: 1;
}

CODEPEN

We trust this guidance will be beneficial.

Answer №4

Here's a different method utilizing Pointer_events

When hovering over an element, you can deactivate the pointer-events on the other one:

$('.first').hover(
  () => { $('.second').css({'pointer-events': 'none'})},
  () => { $('.second').css({'pointer-events': 'auto'})
})

$('.second').hover(
  () => {$('.first').css({'pointer-events': 'none'})},
  () => {$('.first').css({'pointer-events': 'auto'})
})
* {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
  border: 0;
}

body {
  background-image: linear-gradient(45deg, transparent 50%, #aaa 75%);
  background-size: 20px 20px;
}

.wrapper {
  margin-top: 10px;
  margin-left: 10px;
}

.first {
  width: 100px;
  height: 100px;
  background: rgba(255, 0, 0, 0.6);
}

.second {
  width: 99px;
  height: 98px;
  margin-top: -49px;
  margin-left: 50px;
  background: -webkit-linear-gradient(transparent 50%, rgb(255, 0, 0) 50%), -webkit-linear-gradient(0deg, transparent 50%, rgb(255, 0, 0) 50%);
  opacity: 0.6;
}

.first:hover,
.second:hover {
  background: rgba(255, 0, 0, 1);
  opacity: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
  <div class="first" id="first"></div>
  <div class="second" id="second"></div>
</div>

Verify the compatibility of this method, as it may function in most browsers except Safari (at the moment).

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

Adjust the dimensions of the dropdown menu

Objective: How can I adjust the width of a select dropdownlist that is utilizing bootstrap v2? Challenge: I am uncertain about how to modify the width in the context of bootstrap. Additional Information: Keep in mind that there are three dropdownli ...

What is the best way to utilize window.find for adjusting CSS styles?

Incorporating both AJAX and PHP technologies, I have placed specific text data within a span element located at the bottom of my webpage. Now, my objective is to search this text for a given string. The page consists of multiple checkboxes, with each check ...

How to retrieve the same value from multiple selections using Vanilla JavaScript and multiple select options?

Why do we consistently receive the same value and index when using the ctl key to select multiple options? document.querySelector('select').addEventListener('change', function(e) { console.log(this.selectedIndex) console.log(e.ta ...

A guide on extracting individual Json fields and assigning them to separate variables

I have a JSON object that I need to break down into individual fields and then use each field separately. However, the code I wrote below is not functioning correctly and returns "undefined" in the alert message. This is my code snippet: $( document ).r ...

Move a CSS div with animation to a specific fixed position

Is there a way to modify this code so that the ball moves to the right and remains in that position? http://codepen.io/chriscoyier/pen/pBCax You can experiment with the live version of the output by clicking on the link above. body { padding: 30px; } # ...

Positioning a footer at the absolute bottom of a webpage

I am currently working with 2 divs that are absolutely positioned within a relative container. I intend to utilize JavaScript for toggling visibility. .container { position:relative; } .section1 { position:absolute; top:0; left:0; right:0; ...

Utilizing jQuery to assign a value to a SPAN tag

In my code, there is an element with the following syntax: <span id="userName.errors" class="errors">Enter Your User Name </span>. I am interested in utilizing jQuery to delete either the text 'Enter Your User Name' or any element tha ...

What strategies can be implemented to improve the total blocking time in Vue for optimal performance

I'm facing a challenge that I can't seem to resolve. My page has a high total blocking time (2+ sec). Despite trying to load every vue component asynchronously, the issue persists with 2+ sec TBT. I'm puzzled by what could be causing such a ...

Guide to aligning several texts to the right using Bootstrap 4 breadcrumbs

I am looking to implement a breadcrumb using Bootstrap 4.1 that displays the sitemap path on the left and login links on the right. Below is a visual representation of what I aim to achieve: Home/Blog/post Re ...

The Ajax response seems to be heading in the wrong direction

Task: The goal is to fetch and display all fields for a selected customer from the database when a customer is chosen from the select tag. This should be done using Ajax and jQuery, which has been successfully implemented. Here's the JavaScript code ...

Updating React state manually before using the setState function

Currently, I'm delving into React JS and working on a basic todo list project. A snippet of my code looks like this: changeStatus(e, index) { this.state.tasks[index].status = e.target.value; this.setState((prevState) => ({ tasks: p ...

There was an issue stating that valLists is not defined when paginating table rows with AngularJS and AJAX

I found a helpful code snippet on this website for implementing pagination in AngularJS. I'm trying to adapt it to work with data from a MySQL DB table called 'user', but I keep running into an issue where the valLists variable is undefined, ...

What could be causing the issue of the title in req.body to display as 'undefined'?

I am currently learning about NODE JS and practicing working with POST forms from PUG to a NODE JS server. I am facing an issue where the submission input is coming back as 'undefined' when I submit a form from the web browser. In the code snipp ...

Finding the precise top offset position with jQuery upon scrolling – a step-by-step guide

I need help with detecting the offset top of a TR element when it is clicked. It works fine initially, but once the page is scrolled, the offset().top value changes. How can I resolve this issue? $(function() { $('tr').click(function() { ...

Dynamic Filtering of HTML Dropdown Options Based on Another Dropdown Selection

I am facing an issue with multiple HTML dropdowns. My requirement is that upon selecting an option from one dropdown, the next dropdown should get automatically populated. The data to populate these dropdowns is fetched from a database using SQL statements ...

Prevent event propagation when a CSS pseudo-element is active

In my project, there are two elements: .parentElement and .childElement. Both have the :active implemented to appear darker when pressed. The .childElement is nested inside the .parentElement. I am looking for a way to prevent the .parentElement:active fr ...

Discontinuing the mobx autorun feature upon componentWillUnmount

In my componentDidMount, I have the following autorun function: componentDidMount() { this.autoUpdate = autorun(() => { this.setState({ rows: generateRows(this.props.data) }) }) } Unfortunate ...

Phantom.js WebDriver.io Error: Issue with Syntax - DOM Exception 12

Currently conducting tests using webdriver.io and phantom.js. The first test works successfully, providing a list of elements: return client .url(config.host) .waitForVisible('#myvenuelist', 2000) .click('#myvenuelist') ...

Error: Attempting to access the property '_id' of an undefined variable throws a TypeError, despite having body-parser installed

I am currently learning the MEAN stack, but I have hit a roadblock with this error message: TypeError: Cannot read property '_id' of undefined. After searching online, I found suggestions that I need to include body-parser in my server.js file. H ...

Retrieving dynamic id values from input fields using jQuery

Is there a way to retrieve the values from input fields with changing IDs in a jQuery function? <input type="text" id="a_8" name="a_8" value="12"> <input type="text" id="b_8" name="b_8" value="22"> <button type="button" class="btn btn-suc ...