Hi, I have a quick question. I created a CSS hover transition while running JS on the same element and it the CSS works for the first part of the hover effect, but then on the part where you stop hovering over the element, it instantly changes which ruins the transition effect. (I obviously want it to fade back out) I debugged this by removing the JS and it worked but I want to know if I can use it on both to make it look amazing.
Heres my JS:
const scrollElements = document.querySelectorAll(".js-scroll");
const elementInView = (el, dividend = 1) => {
const elementTop = el.getBoundingClientRect().top;
return (
elementTop <=
(window.innerHeight || document.documentElement.clientHeight) / dividend
);
};
const elementOutofView = (el) => {
const elementTop = el.getBoundingClientRect().top;
return (
elementTop > (window.innerHeight || document.documentElement.clientHeight)
);
};
const displayScrollElement = (element) => {
element.classList.add("scrolled");
};
const hideScrollElement = (element) => {
element.classList.remove("scrolled");
};
const handleScrollAnimation = () => {
scrollElements.forEach((el) => {
if (elementInView(el, 1.25)) {
displayScrollElement(el);
} else if (elementOutofView(el)) {
hideScrollElement(el)
}
})
}
window.addEventListener("scroll", () => {
handleScrollAnimation();
});
Heres the html for the element:
<a id="aboutlink">
<section class="backgroundimg scroll-element js-scroll fade-in-bottom">
</a>
<h1 class="textimg" style="margin: 95px 0px 0px 500px; font-weight: 500;">Welcome Test</h1>
<p class="textimg" style="margin: 0; padding: 165px 150px 0px 150px;font-size: 24px;text-align: center;line-height: 36pt;">Test Test Test </p>
</section>
And lastly the CSS corresponding to the element
.backgroundimg {
background-color: rgb(77, 107, 153);
width: 100%;
height: 200px;
.backgroundimg:hover {
background-color: #555555;
-webkit-transition: background-color 2000ms ease-out;
-moz-transition: background-color 2000ms ease-out;
-o-transition: background-color 2000ms ease-out;
transition: background-color 2000ms ease-out;
.scroll-container:nth-of-type(2) {
background-color: rgb(77, 107, 153);;
}
.scroll-container:nth-of-type(even) {
flex-direction: row-reverse;
}
.scroll-element {
min-height: 300px;
height: 600px;
background-color: rgb(77, 107, 153);
width: 100%;
}
@media screen and (max-width: 650px) {
.scroll-container,
.scroll-container:nth-of-type(even) {
flex-direction: column;
align-content: inherit;
}
}
.js-scroll {
opacity: 0;
transition: opacity 500ms;
}
.js-scroll.scrolled {
opacity: 1;
}
.scrolled.fade-in-bottom {
animation: fade-in-bottom 1s ease-in-out both;
}
@keyframes fade-in-bottom {
0% {
-webkit-transform: translateY(50px);
transform: translateY(50px);
opacity: 0;
}
100% {
-webkit-transform: translateY(0);
transform: translateY(0);
opacity: 1;
}
}
Note: this may not be “complete” code as it was extracted from a website project I am working on for a business.