Replace Picture as you Scroll

Is it possible to swap images based on scroll position? For instance:

When scrolling 100px, display img1.jpg

When scrolling 200px, display img2.jpg

When scrolling 300px, display img3.jpg

Here's an example of what I'm looking for.

Any suggestions?

Answer №1

If you want to track scrolling on a webpage, you can utilize the onScroll event to detect when a user scrolls and then implement actions such as changing an image or any other desired effect. To learn more about the onScroll event, you can refer to this link. Below is a basic example of how you can achieve this:

var onScrollHandler = function() {
  var newImageUrl = yourImageElement.src;
  var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
  if (scrollTop > 100) {
     newImageUrl = "img1.jpg"
  }
  if (scrollTop > 200) {
     newImageUrl = "img2.jpg"
  }
  if (scrollTop > 300) {
     newImageUrl = "img3.jpg"
  }
  yourImageElement.src = newImageUrl;
};
object.addEventListener("scroll", onScrollHandler);

Remember to replace yourImageElement with the specific image element you want to modify.

If you have jQuery at your disposal, you can alternatively use the .scroll() method along with .scrollTop() to determine the scrollbar position.

Furthermore, you may explore various scroll/parallax libraries like skrollr for additional functionalities.

Answer №2

$(window).on("scroll touchmove", function() 
{
if ($(document).scrollTop() >= $("#one").position().top && $(document).scrollTop() < $("#two").position().top  ) 
{
$('body').css('background-image', 'url(https://4.bp.blogspot.com/-Ivk46EkgQfk/WWjbo4TdJbI/AAAAAAAAFUo/gUD7JABklsIA1gWIr5LS1slyY4QuTMkEwCLcBGAs/s1600/gambar%2Bwallpaper%2Bmobil.jpg)')
    };
if ($(document).scrollTop() >= $("#two").position().top && $(document).scrollTop() < $("#three").position().top)
{
$('body').css('background-image', 'url(https://i1.wp.com/cdn.catawiki.net/assets/marketing/uploads-files/45485-8bdcc8479f93d5a247ab844321b8b9d5e53c49a9-story_inline_image.jpg)')
    };
   if ($(document).scrollTop() >= $("#three").position().top && $(document).scrollTop() < $("#four").position().top ) 
   {
$('body').css('background-image', 'url(https://s-media-cache-ak0.pinimg.com/originals/e1/7a/03/e17a0385726db90de1854177d4af2b4f.jpg)')
   };
   if ($(document).scrollTop() >= $("#four").position().top) 
   {
$('body').css('background-image', 'url(https://www.wallpaperup.com/uploads/wallpapers/2015/02/13/621414/6fc33c3ae65a58f9bb137f5cf011aebc.jpg)')
   };
  
});
*{
margin:0;
padding:0;
 }
.main{
width:100%;
height:100vh;
background-image:url('https://4.bp.blogspot.com/-Ivk46EkgQfk/WWjbo4TdJbI/AAAAAAAAFUo/gUD7JABklsIA1gWIr5LS1slyY4QuTMkEwCLcBGAs/s1600/gambar%2Bwallpaper%2Bmobil.jpg');
background-size:100% 100%;
background-attachment:fixed;
transition: 1000ms;
}
section{
width: 100%;
min-height: 1px;
}
.content{
width:50%;
min-height:1px;margin-top:10%;
margin-left:10%;
color:white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body class='main'>
<section id="one">
<div class='content'>
<h1 style='font-size:5vw;'>first heading</h1>
<p style='font-size:3vw;' >description</p>
</div>
</section>
<section id="two" style='margin-top:100vh'>
<div class='content'>
<h1 style='font-size:5vw;'>second heading</h1>
<p style='font-size:3vw;'>description</p>
</div>
</section>
<section id="three" style='margin-top:100vh' >
<div class='content'>
<h1 style='font-size:5vw;'>third heading</h1>
<p style='font-size:3vw;'>description</p>
</div>
</section>
<section id="four" style='margin-top:100vh' >
<div class='content' style='margin-bottom:10%;'>
<h1 style='font-size:5vw;'>fourth heading</h1>
<p style='font-size:3vw;'>description</p>
</div>
</section>
</body>
</html>

documentation

create a web folder first.
create a img sub folder  // place  all images into this folder
now create three files // in web folder
index.html 
css.css
js.js 

copy code given bellow and paste it.
save the program.
finally run the program 

click on this link to see the video :https://www.youtube.com/watch?v=V97wCVY_SrQ
visit our website for full documentation :

index.html

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href='css.css' rel='stylesheet' type='text/css'/>
    <script src='js.js'></script> 
...

css.css

...

js.js

...

Answer №3

After stumbling upon this old thread, I felt compelled to share my experience with implementing a similar feature on my website. While I initially found it challenging to implement, I eventually developed my own function that is easier to understand but still has some bugs. For example, if the user uses the scroll bar instead of the mouse scroll wheel, the image will not change. Hopefully, my workaround can be helpful to you:

<html>

<head>
  <script>
    function f() {
      t1.src = "https://igu3ss.files.wordpress.com/2012/09/chess_king_4.jpg"
      t1.height = "319"
      t1.width = "330"
    }

    function f2() {
      t1.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d3/Chess_piece_-_Black_queen.JPG/130px-Chess_piece_-_Black_queen.JPG"
      t1.height = "319"
      t1.width = "330"
    }

    function f3() {
      t1.src = "https://asmoodle.asmadrid.org/blog/s16240/wp-content/uploads/sites/56/2014/12/protourney_knight_black_400.jpg"
      t1.height = "244"
      t1.width = "330"
    }

    function f4() {
      t1.src = "https://thumbs.dreamstime.com/x/chess-knight-white-background-29811348.jpg"
      t1.height = "244"
      t1.width = "350"
    }

    function f5() {
      t1.src = "http://cdn.craftsy.com/upload/3703789/pattern/115774/full_7439_115774_ChessKnightMachineEmbroideryDesign_1.jpg"
      t1.height = "319"
      t1.width = "350"
    }
  </script>
</head>

<body>
  <div align="center" style="position: fixed; z-index: 20; left:38.5%; top:200">
    <img src="no.png" height="319" width="330" name="t1">
  </div>
  </div>
  <div class="container" onmouseover="f3()" style="padding:0; margin:0; width:100%;">
    <img src="https://pixabay.com/static/uploads/photo/2016/01/11/22/05/background-1134468_960_720.jpg" width="100%">
  </div>
  <br>
  <br>
  <div class="container" onmouseover="f4()" style="padding:0; margin:0; width:100%;">
    <img src="https://image.freepik.com/free-photo/lens-flare-abstract-backgound_21276999.jpg" width="100%">
  </div>
  <br>
  <br>
  <div class="container" onmouseover="f5()" style="padding:0; margin:0; width:100%;">
    <img src="https://image.freepik.com/free-photo/lens-flare-abstract-backgound_21276999.jpg" width="100%">
  </div>
  <br>
  <br>
  <div class="container" onmouseover="f()" style="padding:0; margin:0; width:100%;"></div>
</body></html>
Cheers!! Happy Coding.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The back-to-top button guides users back to their last visited page

I'm excited to explore AngularJS and I want to add two "return to top" buttons on different pages. Here's what I have so far: Page 1: <h1 id = "top"> .......... <a href="#top" target = "_self">Return to Top</a> Page ...

Generating a fresh array by extracting values from an existing array in a loop

I am currently working with an array of strings named groups and I am using a forEach loop to iterate through it. My goal is to create a new array where each string becomes the name of the array. I attempted to initialize the arrays with let [group] = [], ...

Content enclosed in a div tag and displayed within the same

I need assistance in converting a PSD file into two cards. The content within the card should resemble this. Can anyone provide guidance on how to achieve this? Below is the code I am currently working with: .container { margin-top: 10px; } .ca ...

Exploring IdentityServer3: A Deep Dive into OAuth Flows and Varied Strategies

After developing a REST Web API application, I want to provide other developers with the capability to access those APIs on behalf of the user. To achieve this, I have implemented OAuth authentication with IdentityServer3. Currently, I have successfully ge ...

Tips for incorporating images as radio buttons

Can anyone assist me in setting up a straightforward enabled/disabled radio button grouping on my form? My idea is to utilize an image of a check mark for the enabled option and an X for disabled. I would like the unselected element to appear grayed out ...

What are the reasons for the dynamic exclusion of an element in Angular?

Can someone help me figure out why my data is not being added dynamically using ng-repeat? I have entered the "name" which should be added to the data, but it is not displaying in the UI. You can see the issue in this demo app.controller("studentcntr", ...

Issue with implementing autocomplete using AJAX and PHP for multiple input fields

HTML code: <table> <tr> <td align="center"> <label for="InputBox1"><b>~</b><font color="red">*</font>: &nbsp;</label> </td> </tr> <tr> <td align="center"> <div id="1"> ...

Issue "Invalid UTF-8" encountered while compiling sass using @import

Here is the structure of my project: project assets scripts styles app.scss bower_components node_modules public css app.css js bower.json gulpfile.js package.json I am using gulp-sass to compile app.scss into ap ...

Using multiple box-shadow declarations in Sass

I'm struggling to create a Sass mixin for the box-shadow property. Here's a snippet of the existing code: #someDiv { -moz-box-shadow:0 0 5px rgba(0,0,0,.25); } #someOtherDiv { -moz-box-shadow:0 0 5px rgba(0,0,0,.25) inset; } #theLastDiv { ...

Declare `document.body` as the designated container element for the material-ui Tooltip

The issue: I need to show a tooltip pointing to an element (referenceEl) from the left. The referenceEl is located within a container that has a limited width of 60px and has the css properties overflow: hidden applied. Due to the tooltip being appended af ...

Discovering if the array data is already present in Angular can be accomplished by using specific methods

Here is the snippet of code: data = [ { 'id': 'asdjxv', 'username': 'emma', }, { 'id': 'asqweja', 'username': 'adam', }, { ...

Animating various image widths using jQuery

I've been on a quest for a solution for quite some time to no avail, so it's time to seek help. My goal is to utilize the .animate() function in order to alter the size of an image upon clicking. The image should initially appear as a thumbnail s ...

Tips for aligning spin.js spinner in the center of a bootstrap 3 modal?

I'm attempting to showcase and center the spin.js spinner within a Bootstrap 3 modal. Despite successful implementation in IE and FF using the code below, I am encountering issues in Chrome, Safari Desktop, Chrome IOS, Safari IOS. The problem appears ...

Arranging React Bootstrap columns in a way that the column on the right appears above the column on the left

Is there a way to use React Bootstrap to create a layout with two columns side by side, and have the column on the right stack on top of the column on the left when the screen size is reduced? Check out the code snippet below: import "./styles.css&qu ...

When hovering over CSS cards, they transform into a zigzag pattern and the text spills out of the box with overflow

I'm having an issue with my webpage where the text on my CSS cards is overflowing and not staying within the card. Additionally, when I hover over an element, the remaining CSS cards are arranged in a zig-zag manner. Here's the code snippet for r ...

Could the long-term consequences of utilizing '--force' or '--legacy-peer-deps' be detrimental?

I'm currently working on a react-native project and encountering an error while trying to install the native-base library... npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-prote ...

How to get the most out of the $scope variable?

Is it possible to assign a regular JavaScript variable the current value of an Angular $scope variable without having their values binded together? //$scope.var1 is set to a specific value, for example, 5 var v2 = $scope.var1; //$scope.var1 is then update ...

Leveraging nodemailer for automated email delivery

Hey there! I'm looking for some advice on how to set up scheduling with emailing using nodemailer. Ideally, I'd love to be able to schedule emails to send every day at 9am within a web app using nodemailer. However, I'm not sure where to st ...

Updating elements with jQuery each/ajax during a loop may not take effect

My goal is to refresh a list after receiving data from an ajax call. The process looks like this: $.ajaxSetup({ async: false }); $.ajax(jsonUrl, { dataType: "json", success: function(data) { $.each(data.list, function(k,v) { ...

In the Firebug console, Ajax posts are highlighted in a vibrant red color

Upon executing the code provided, the Firebug was enabled. While submitting the form, in the console, the message "post to login_submit.php" appeared in red. However, there was no response received as well. <!DOCTYPE html> <html> ...