How-To JQuery

Changing image on scroll Position

Hello Folks! welcome back to  my channel, In this article we are going explain how to make image change on certain scroll level using jQuery, its not much a big deal we’ll do it in simple way just follow the few steps as below.

We have used only 2 images but it can easily be changed for multiple images. We are implemented the images one by one of each other, this will makes sure that only one image is visible or Block at a time. When we will scroll, we are taking scroll percentage of the current page. By doing this the next image overlays on the top of First image and the Second image will becomes visible.

The ideal question is, How can we change the image on certain scroll level? It’s much simpler than you think!

So let’s get started!! you can directly Download it from here

Step 1 is to Create a HTML page and Add the following Codes :

Here i’m displaying scroll level, so that developer can easily understand, on how much scroll, the EVENT should trigger.

<p id="scrollId"> </p> //This Paragraph is to Display Scroll Percentage.

<br> <br> //Line Brakes
<div class="imageDiv">
<img src="full.png" id="img1">
<img src="img2.PNG" id="img2">
</div>
Step 2 : Need to add CSS for the Image DIV
<style type="text/css">
html{
height:100%;
}
body{
height:1000%;   
}
.imageDiv img{
position: fixed;
width: 200px;
}

p{
position: fixed;
margin-bottom: 2%;
}
</style>

Step 3 : The Last step is to add jQuery Script
 
//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>
 

As you can see the above script, we have taken jQuery from CDN path. after that we have implemented jQuery if and jQuery Scroll.

if you find any difficulties please comment us in the below comment box.

Happy coding 🙂

About the author

Vishwas

A coder who is trying to solve some problems via "Procoders", Software Engineer By Profession, WEB Enthusiast, Hobby Blogger. I love to share Tech Ideas and like to learn and explore new things and Technologies.

1 Comment

Click here to post a comment