In this post we are going to learn how to change images on scroll using jquery
How can we change the image on scroll? It’s much simpler than you think!
Let’s create a code & see the result.
Step 1 : Create a HTML page and Add the following Codes :
<p id=”scrollId”> </p> //This Paragraph is to Display Scroll Percentage.
<br> <br> //Line Brakes
<div class=”imageDiv”>
<img src=”image01.jpeg” id=”img1″>
<img src=”image02.jpeg” id=”img2″>
</div>
Step 2 : Adding CSS
<style type=”text/css”>
html{
height:100%;
}
body{
height:1000%; //Adding additional height to body
}
.imageDiv img{
position: fixed;
height:400px;
width: 200px;
}
p{
position: fixed;
margin-bottom: 2%;
}
</style>
Step 3 : Adding Jquery
//calling jquery
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js”></script>
<script type=”text/javascript”>
$(window).on(‘scroll’, function(){
var s = $(window).scrollTop(),
d = $(document).height(),
c = $(window).height();
var scrollPercent = (s / (d – c)) * 100;
document.getElementById(‘scrollId’).innerHTML = scrollPercent;
console.log(scrollPercent); //Displaying scroll percentage in console
if(scrollPercent < 20){
document.getElementById(‘img1’).style.display = “block”;
document.getElementById(‘img2’).style.display = “none”;
}
else if(scrollPercent > 20 && scrollPercent < 30){
document.getElementById(‘img1’).style.display = “none”;
document.getElementById(‘img2’).style.display = “block”;
}
})
</script>
Final Result :
<style type=”text/css”>
html{ height:100%; }
body{ height:1200px; }
.imageDiv img{
position: fixed;
height:400px;
width: 200px;
} p{
position: fixed;
margin-bottom: 2%;
}
</style>
<p id=”scrollId”></p>
<br><br>
<div class=”imageDiv”>
<img src=”image01.jpg” id=”img1″>
<img src=”image01.jpg” id=”img2″>
</div>
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js”></script>
<script type=”text/javascript”>
$(window).on(‘scroll’, function(){
var s = $(window).scrollTop(),
d = $(document).height(),
c = $(window).height();
var scrollPercent = (s / (d – c)) * 100;
document.getElementById(‘scrollId’).innerHTML = scrollPercent;
// console.log(scrollPercent);
if(scrollPercent < 20){
document.getElementById(‘img1’).style.display = “block”;
document.getElementById(‘img2’).style.display = “none”;
}
else if(scrollPercent > 20 && scrollPercent < 30){
document.getElementById(‘img1’).style.display = “none”;
document.getElementById(‘img2’).style.display = “block”;
}
})
</script>
Add Comment