Change Image Dynamically when User Scrolls Down | Set 2
There may be situations where the image would need to change dynamically based on the user’s input. In this case, when the user scrolls down.
- Setting up a scroll event listener to know the user has scrolled the page.
- Calculating the pixels that have been scrolled up vertically by the user. It is accessed by using the scrollTop element.
- Using that value to change the source of the image dynamically.
Example 1: In this example, we will change the source of the image whenever the page is scrolled 150 pixels vertically. The page consists of an image and a section for the text. They are styled through internal CSS.
window.onscroll listener would call a function every timewhen the user scrolls. Then, the called function selects the image using
document.getElementById("myImage") and changes the source path of the image whenever the scrolled pixels crosses 150px.
Example 2: In this example, we will change the arrangement of the images dynamically depending on how much the user has scrolled down. The page consists of four images given a sticky position at the bottom of the page.
The function called by the scroll listener shuffles the source of the image dynamically. This gives us a spinning look for the images.