Issue
I need to make an animation that change a text from opacity:0 to 1 when I drag the pointer to the box so I use setInterval() to plus a small value to the 'opacity' through each iteration and I don't know why it can't update the value for the 'opacity'.
Thanks for support!
const getPhara = document.querySelectorAll(".phara-move");
const getCard = document.querySelectorAll(".up-mask");
getCard.forEach((element, index) => {
element.onmouseover = () => {
var opa;
setInterval(() => {
opa = parseInt((getComputedStyle(getPhara[index])).opacity);
console.log(opa);
opa += 0.2;
console.log(opa);
console.log(`${opa}`);
// getPhara[index].setAttribute("style", `opacity: ${opa};`);
getPhara[index].style.opacity = `${opa}`;
}, 1000);
}
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.phara-move {
opacity: 0;
}
.up-mask {
width: 50%;
height: 100px;
border: 1px solid black;
}
</style>
</head>
<body>
<div class="gallery__item">
<div class="up-mask"></div>
<div class="phara-move">Lorem ipsum dolor sit amet consectetur adipisicing elit.</div>
</div>
<div class="gallery__item">
<div class="up-mask"></div>
<div class="phara-move">Lorem ipsum dolor sit amet consectetur adipisicing elit.</div>
</div>
<script src="./bug.js"></script>
</body>
</html>
Solution
Use css transitions
Looking at the code, it appears that you want to fade in text when the mouse hovers over another element.
You can do that without any JavaScript and eliminate the problem with the timers. The following css uses transition to create the fade in/out effect. And we use the plus sibling selector to place the effect on the sibling after the element being hovered.
.mask-up + .phara-move {
opacity: 0;
transition: opacity 2s;
}
.mask-up:hover + .phara-move {
opacity: 1;
}
Snippet
Review and run the snippet to understand how it works.
.gallery__item {
margin: 1rem;
}
.mask-up {
width: 50%;
height: 50px;
border: 1px solid black;
}
.mask-up + .phara-move {
opacity: 0;
transition: opacity 2s;
}
.mask-up:hover + .phara-move {
opacity: 1;
}
<div class="gallery__item">
<div class="mask-up">Hover over me</div>
<div class="phara-move">
Lorem ipsum dolor sit amet consectetur adipisicing elit.
</div>
</div>
<div class="gallery__item">
<div class="mask-up">Hover over me</div>
<div class="phara-move">
Lorem ipsum dolor sit amet consectetur adipisicing elit.
</div>
</div>
Answered By - Yogi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.