I am looking to achieve a hover effect that displays a border around an element without actually adding the border to the element itself, as shown in this image:
https://i.sstatic.net/iFpCA.png
The challenge I'm facing is that I want to allow users to change styles, so directly adding a border or outline to the element won't work as it will be affected by user style changes.
Here is my approach to solving this:
- Created an overlay
div
positioned usingposition: absolute
- Inserted a nested
div
within the overlay also set toabsolute
- Implemented
onmouseover
andonmouseout
event listeners on the overlaydiv
to gather information about the element's position and size
However, the issue I encountered is that the overlay prevents events from firing on elements beneath it, which I need for the nested element's information. I've tried adjusting the z-index
but it didn't work as expected.
So, what would be the best way to achieve this effect?
PS: The screenshot is from Webflow's visual builder, and I am unsure of their method for achieving this.
Here is the relevant code snippet:
var outlineContainer = document.querySelector('#content-container');
outlineContainer.onmouseover = outlineContainer.onmouseout = handler;
function handler(event) {
var hoverOutline = document.querySelector('.hover-outline');
if (event.type == 'mouseover') {
console.log(event.target.tagName);
var clientRects = event.target.getBoundingClientRect();
hoverOutline.style.width = `${clientRects.width}px`;
hoverOutline.style.height = `${clientRects.height}px`;
hoverOutline.style.transform = `translate(${event.target.offsetLeft}px,${event.target.offsetTop}px)`;
}
if (event.type == 'mouseout') {
hoverOutline.style.width = 0;
hoverOutline.style.height = 0;
hoverOutline.style.left = 0;
hoverOutline.style.top = 0;
}
}
#content-container {
border: 2px solid black;
background-color: white;
padding: 50px;
position: relative;
height: 100%;
}
.overlay {
position: absolute;
left: 0;
top: 0;
height: 100%;
width: 100%;
z-index: 2;
}
.hover-outline {
position: absolute;
border: 2px solid orange;
z-index: 6;
top: 0px;
left: 0px;
z-index: 3;
}
.content {
z-index: 4;
}
<div id="content-container">
<div class="overlay">
<div class="hover-outline"></div>
</div>
<div class="content">
<div class="component">
<label>Hi</label>
</div>
<div class="component">
<label>Text Field</label>
<span class="wrapper">
<input type="text" placeholder="Text Input Field" />
</span>
</div>
</div>
</div>