My CSS keyframe animation uses a CSS variable as an animation property, which is defined in jQuery. The animation works perfectly in Chrome and Firefox, but on Safari and mobile browsers, only parts of the animation that do not involve the variable work correctly.
I've been troubleshooting this issue extensively...
- I have tested on the latest browser versions.
- Checking Developer tools in Safari confirms that the variable is correctly defined (e.g. 1200px).
- If I hard-code the variable value in the CSS, the animation functions correctly.
- However, if I hard-code the variable value in jQuery instead of calculating it, the animation fails.
- Using the variable as a property in the element selector itself positions the element as expected.
- I tried using "transform: translateY(...)" instead of "top:" with no change in results.
- Occasionally, leaving the window open causes the animation to start working properly. However, I cannot replicate this consistently.
Based on all this, it seems like there's an issue with defining the variable in jQuery (which also did not work with plain JavaScript) and using it in the animation.
Any insights into what might be happening?
function refHeight() {
if ($('#main-content').length != 0) {
$(':root').css('--varheight', Math.round($('#main-content').outerHeight()) + 'px');
}
}
window.addEventListener('load', refHeight);
window.addEventListener('resize', refHeight);
:root {
--hardvarheight: 75vh;
}
#main-content {
width: 100%;
height: 75vh;
}
.item {
width: 75px;
height: 50px;
font-size: 80%;
}
.one {
animation: animOne 3s linear infinite alternate;
position: absolute;
background-color: pink;
}
.two {
position: absolute;
top: calc(var(--varheight) / 100 * 50);
left: 50vw;
background-color: lightblue;
}
.three {
animation: animThree 3s linear infinite alternate;
position: absolute;
background-color: lightgreen;
}
@keyframes animOne {
0% {top: calc(var(--varheight) / 100 * 10); left: 40vw;}
50% {top: calc(var(--varheight) / 100 * 20); left: 50vw;}
100% {top: calc(var(--varheight) / 100 * 10);left: 60vw;}
}
@keyframes animThree {
0% {top: calc(var(--hardvarheight) / 100 * 80); left: 40vw;}
50% {top: calc(var(--hardvarheight) / 100 * 90); left: 50vw;}
100% {top: calc(var(--hardvarheight) / 100 * 80); left: 60vw;}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="main-content">
<div class="item one">Animated Using jQuery Variable</div>
<div class="item two">Positioned Using jQuery Variable</div>
<div class="item three">Animated Using CSS Variable</div>
</div>