JSFiddle - React, Tailwind, and code Playground
HTML
<h1>Scroll me</h1>
<div>
<img src="https://images.unsplash.com/photo-1581888227599-779811939961?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1867&q=80" />
</div>
<div id="debug">
</div>
CSS
@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@100&display=swap');
body {
height: 400vh;
font-family: Montserrat, sans;
}
div {
position: fixed;
}
#debug {
top: 1em;
right: 1em;
}
JavaScript
const MAX_HEIGHT = 300;
const MIN_HEIGHT = 100;
const MAX_TARGET = 500;
const MIN_TARGET = 200;
var image = document.querySelector('img');
var ratio = 0;
// -------------------------------------------------------
window.addEventListener('scroll', function() {
// Determine ratio of scroll to target
ratio = (window.scrollY - MIN_TARGET) / (MAX_TARGET - MIN_TARGET);
// Normalize ratio
ratio = Math.min(1, Math.max(0, ratio));
// Set height based on ratio
image.height = MIN_HEIGHT + (MAX_HEIGHT - MIN_HEIGHT) * ratio;
});
// -------------------------------------------------------
window.addEventListener('scroll', function() {
debug.innerHTML = [
window.scrollY,
ratio.toFixed(3),
].join('<br>');
})
window.dispatchEvent(new Event('scroll'));