Why animate: Animation is not tied specifically to behavior, but to a block. Hence, we can change the style smoothly when the block reaches a certain place.
What do you need: For two days, on the evening shift, I tried to write the code exactly in such a way that it would be as similar as possible to sticky, but everything breaks with transition.
___My JavaScript code now has this behavior.
//This code is not working correctly
const navigation = document.querySelector('.menu');
const { offsetTop } = navigation;
window.addEventListener('scroll', () => {
const recY = navigation.getBoundingClientRect().y;
const positionHtml =
(document.documentElement && document.documentElement.scrollTop) ||
document.body.scrollTop;
if (recY < 1) {
navigation.style.top = positionHtml;
}
else if (positionHtml > offsetTop) {
navigation.style.top = offsetTop;
}
});
Before that, I was adding a class or removing it, but this revealed one big problem related to css.
const navigation = document.querySelector('.menu');
const getMatrix = (selector, lastIndex) => {
const transform = window
.getComputedStyle(selector, null)
.getPropertyValue('transform');
const dataTransform = transform.match(/-?\d+\.?\d+|\d+/g);
return +dataTransform[dataTransform.length - lastIndex];
};
const { offsetTop } = navigation;
const savaPos = getMatrix(navigation, 1);
window.addEventListener(
'scroll',
() => {
const doc =
(document.documentElement && document.documentElement.scrollTop) ||
document.body.scrollTop;
if (navigation.classList.contains('s') && doc >= savaPos) return;
else if (doc >= offsetTop && doc >= savaPos) {
navigation.classList.add('s');
} else if (doc <= savaPos) {
navigation.classList.remove('s');
}
},
{ passive: true }
);
css
.s {
position: fixed;
transform: translateY(0);
width: 100%;
height: auto;
}
.menu {
display: flex;
transform: translateY(100px);
width: 100%;
padding: 15px;
background-color: #14151a;
/* transition: transform 0.1s; */
}
This code works just as well as sticky, but you can't apply animation.
The fact is that when I change one position to another, for example static to fixed, I get the wrong behavior.
Now I want to try to leave the old code and clean up or give transition separately, waiting for some time in ms, after adding or removing the class.
/* transition: all 1.1s; */