Table of Contents
Css scroll animation | scroll animation html css javascript code – codewithrandom
Welcome🎉 to Code With Random blog. In this blog, we learn that how we create a Css scroll animation. We use HTML, and javascript for this Css scroll animation. Hope you enjoy our blog so let’s start with a basic HTML structure for a Css scroll animation.
HTML code for scroll animation
<body>
<h1>Scroll animation codewithrandom</h1>
<div class="box"><h2>image</h2></div>
<div class="box"><h2>image</h2></div>
<div class="box"><h2>image</h2></div>
<div class="box"><h2>image</h2></div>
<div class="box"><h2>image</h2></div>
<div class="box"><h2>image</h2></div>
<div class="box"><h2>image</h2></div>
</body>
There is all HTML code for the scroll animation. Now, you can see output without CSS, then we write css & javascript for the scroll animation.
output
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap');
* {
box-sizing: border-box;
}
body {
background-color: #eee;
font-family: 'Roboto', sans-serif;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
margin: 0;
overflow-x: hidden;
}
h1 {
margin: 10px;
}
.box {
background: url(https://source.unsplash.com/1600x900/?nature,water) ;
color: #fff;
display: flex;
align-items: center;
justify-content: center;
width: 300px;
height: 200px;
margin: 10px;
border-radius: 6px;
box-shadow: 2px 4px 5px rgba(0, 0, 0, 0.3);
transform: translateX(400%);
transition: transform 0.4s ease;
}
.box:nth-of-type(even) {
transform: translateX(-400%);
}
.box.show {
transform: translateX(0);
}
.box h2 {
font-size: 45px;
}
Now we have completed our CSS section, Here is our updated output CSS.
output
Now add javascript for showing image & scroll animation functionality.
Javascript code for scroll animation
const boxes = document.querySelectorAll('.box')
window.addEventListener('scroll', checkBoxes)
checkBoxes()
function checkBoxes() {
const triggerBottom = window.innerHeight /5 * 4
boxes.forEach(box => {
const boxTop = box.getBoundingClientRect().top
if(boxTop < triggerBottom) {
box.classList.add('show')
} else {
box.classList.remove('show')
}
})
}
Final output
Now we have completed our javascript section, Here is our updated output with javascript. Hope you like the simple scroll animation. you can see output video and project screenshots. See our other blogs and gain knowledge in front-end development. Thank you 🙏💕
Check out more…..
In this post, we learn how to create an scroll animation using simple HTML & CSS and javascript. If we made a mistake or any confusion, please drop a comment to reply or help you in easy learning.