I wanted a smooth transition of background: linear-gradient
color when scrolling. It works fine in Chrome, but in Firefox the transition is instantaneous. I have no idea what im doing wrong
On scroll, change class for the div from item-static
to item-sticky
.
// Initial state
const target = document.getElementsByClassName("target");
const w_width = 651;
var scrollPos = 0;
changeTargetClass();
checkWindowSize();
window.addEventListener('resize', checkWindowSize);
function checkWindowSize() {
if (window.innerWidth > w_width) {
// adding scroll event
window.addEventListener('scroll', changeTargetClass);
} else {
window.removeEventListener('scroll', changeTargetClass);
target[0].classList.add('static-item')
}
}
function changeTargetClass() {
scrollPos = (document.body.getBoundingClientRect()).top;
setupTarget()
}
function setupTarget() {
if (scrollPos >= 0) {
target[0].classList.add('static-item')
target[0].classList.remove('sticky-item')
} else {
target[0].classList.remove('static-item')
target[0].classList.add('sticky-item')
}
}
@property --myColor1 {
syntax: '<color>';
initial-value: rgba(85, 85, 249, 1);
inherits: false;
}
@property --myColor2 {
syntax: '<color>';
initial-value: rgb(255, 255, 255);
inherits: false;
}
.target {
top: 0;
}
.flex-container {
display: flex;
align-items: center;
justify-content: space-between;
top: 0;
z-index: 3;
background: white;
}
.sticky-item {
position: sticky;
--myColor1: rgb(255, 255, 255);
--myColor2: rgb(255, 255, 255);
transition: --myColor1 1s ease-in-out, --myColor2 1s ease-in-out;
background: linear-gradient(180deg, var(--myColor1) 0%, var(--myColor2) 100%);
}
.static-item {
position: static;
--myColor1: rgba(85, 85, 249, 1);
--myColor2: rgb(255, 255, 255);
transition: --myColor1 1s ease-in-out, --myColor2 1s ease-in-out;
background: linear-gradient(180deg, var(--myColor1) 0%, var(--myColor2) 100%);
}
<div class="target static-item"> Lorem ipsum dolor sit amet consectetur adipisicing elit. Sapiente alias quod ullam non</div>
<div class="big-box" style="height: 120vh; background: black;"></div>
2
Answers
kinda resolved my question reading this thread
and demo https://codepen.io/fentress8975/pen/LYagxmX
The issue you’re encountering with Firefox likely stems from its handling of CSS custom properties (–myColor1 and –myColor2) within the transition property.
It seems like Firefox might not fully support transitions of custom properties like you defined it.
Instead of transitioning the custom properties directly, you can transition the opacity of the .target element, which indirectly transitions the colors defined by the custom properties. This approach tends to be more widely supported across browsers.