I'm trying to make a clip-path inside an element which follows the cursor. The Clip-Path should only appear inside the element, therefore I use getBoundingClientRect(). It works with the first element, but I would like to make it run on several elements (with class .banner).
I've made a codepen with all the code, hoping someone can figure it out...:
https://codepen.io/gerrit-dolde/pen/oNpXLov
<div class="container">
<section class="underground"></section>
<section class="banner"></section>
</div>
<div class="container">
<section class="underground"></section>
<section class="banner"></section>
</div>
:root {
--x: 0px;
--y: 0px;
}
*{
margin:0;
padding:0;
}
body {
min-height: 100vh;
background:#000;
overflow-x: hidden;
}
.container {
max-width: 800px;
margin: 150px auto;
box-sizing: border-box;
position: relative;
height: 400px;
padding: 0;
}
.underground {
position: absolute;
width: 800px;
height: 400px;
background: url('https://upload.wikimedia.org/wikipedia/commons/e/e7/Everest_North_Face_toward_Base_Camp_Tibet_Luca_Galuzzi_2006.jpg');
background-size: cover;
filter: grayscale(100%) sepia(0) brightness(70%);
}
.banner {
position: absolute;
width: 800px;
height: 400px;
background: url('https://upload.wikimedia.org/wikipedia/commons/e/e7/Everest_North_Face_toward_Base_Camp_Tibet_Luca_Galuzzi_2006.jpg');
background-size: cover;
display: flex;
justify-content: center;
align-items: center;
clip-path: circle(0px at var(--x) var(--y)) !important;
transition: 0.15s;
z-index: 200;
filter: grayscale(0%);
}
.container:hover .banner {
clip-path: circle(200px at var(--x) var(--y)) !important;
transition: 0.15s;
}
const container = document.querySelector(".container");
const banner = document.querySelector(".banner");
container.addEventListener("mousemove", function(e) {
var xPosition = e.clientX - container.getBoundingClientRect().left;
var yPosition = e.clientY - container.getBoundingClientRect().top;
banner.style.setProperty('--x', xPosition + "px");
banner.style.setProperty('--y', yPosition + "px");
}
);
You should set the event on eavh fo the cointainers sepertly fixed it for you:
const container = document.querySelectorAll(".container");
container.forEach(elm=>elm.addEventListener("mousemove", function(e) {
const cur= e.currentTarget;
const banner = cur.querySelector(".banner");
var xPosition = e.clientX - cur.getBoundingClientRect().left;
var yPosition = e.clientY - cur.getBoundingClientRect().top;
banner.style.setProperty('--x', xPosition + "px");
banner.style.setProperty('--y', yPosition + "px");
}
));