Parallax Cards
HTML
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cards</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="flexCard">
<div class="backgroundCard1">
<div class="text">
<p class="bold">Sommerfest</p>
<p class="klein">Am 31.07.2023</p>
</div>
</div>
<div class="backgroundCard2">
<div class="text">
<p class="bold">Herbstfest</p>
<p class="klein">Am 31.10.2023</p>
</div>
</div>
<div class="backgroundCard3">
<div class="text">
<p class="bold">Winterfest</p>
<p class="klein">Am 31.12.2023</p>
</div>
</div>
</div>
<script src="main.js"></script>
</body>
</html>
CSS
body {
font-family: sans-serif;
background: lightgrey;
}
.flexCard {
display: flex;
justify-content: center;
}
[class^=background] {
background-image: url(#);
width: 300px;
height: 400px;
margin: 0 20px;
position: relative;
}
.backgroundCard1 {
background-position: 700px 1000px;
}
.backgroundCard2 {
background-position: 800px 800px;
}
.backgroundCard3 {
background-position: 600px 600px;
}
.text {
font-size: 1.8em;
transition: 0.25s;
position: absolute;
bottom: 0;
color: white;
padding: 0 10px;
}
.textMouse {
background: rgb(64, 64, 64);
width: calc(100% - 20px);
transition: 0.5s;
}
.bold {
font-weight: bold;
}
.klein {
font-size: 0.7em;
}
JS
let cards = document.querySelectorAll('[class^="backgroundCard"]');
let text = document.querySelectorAll(".text");
cards.forEach(addMouse);
function addMouse(elem, index) {
elem.addEventListener("mouseenter", (e) => {
elem.style.transition = `0s`;
text[index].classList.add("textMouse");
let startBackX = parseFloat(getComputedStyle(e.currentTarget).backgroundPositionX);
let startBackY = parseFloat(getComputedStyle(e.currentTarget).backgroundPositionY);
let startX = e.offsetX;
let startY = e.offsetY;
elem.addEventListener("mousemove", eve => {
if (eve.currentTarget === eve.target) {
elem.style.backgroundPositionX =
`${startX - eve.offsetX + startBackX}px`;
elem.style.backgroundPositionY =
`${startY - eve.offsetY + startBackY}px`;
}
});
elem.addEventListener("mouseout", () => {
elem.style.backgroundPositionX = `${startBackX}px`;
elem.style.backgroundPositionY = `${startBackY}px`;
elem.style.transition = "0.5s";
});
elem.addEventListener("mouseleave", () => {
text[index].classList.remove("textMouse");
});
});
}