I am a complete beginner in JS and front-end. I am working on a website and I have an image in this div with the id main-image
.
When the user scrolls down the image I want it to go left slowly and then delete the image.
var x = 0;
var screenWidth = window.innerWidth;
window.onscroll = function() {
var box = document.getElementById("main-image");
setInterval(function() {
if (x <= screenWidth) {
x++;
box.style.left = x + "px";
} else {
box.style.display = "none";
}
}, 10);
}
.site-header {
background-image: url("https://images.pexels.com/photos/2159065/pexels-photo-2159065.jpeg?auto=compress&cs=tinysrgb&fit=crop&h=627&w=1200");
height: 100vh;
background-repeat: no-repeat;
background-size: cover;
justify-content: center;
position: relative;
}
#main-image {
position: marker;
left: 0;
transition: ease-out;
}
<div class="container-fluid site-header" id="main-image">
<div class="image-on-text-container bg-secondary">
<span class="site-brand"></span>
</div>
</div>
I wrote this script for this, but it’s moving badly. I want it to move slower, and maybe with some effect, but I don’t know how.
3
Answers
change these two blocks:
and this:
Calculate the
y
delta instead and animate transition over a timing value of i.e:0.Ns
and translate the x coordinate over that delta value multiplied by 100 to get the percentage value. Don’t forget to addoverflow: hidden;
to a parent elementAnimating elements through their position values (e.g. left) has its drawbacks and does not render as smoothly as translates do, since it cannot be purely calculated by the gpu. See a more detailed explanation here.
Here is an example with transform: translatex() set as a global CSS variable.