xxxxxxxxxx
/*This is the CSS*/
/* Style the img element with the sticky position */
img#stickyImg {
position: sticky;
right:0;
}
#section{
height:1000px;
}
div[class*="div_"]{
height:1000px;
}
.sticky__image img{
position:absolute;
top:50%;
right:0;
transform:translate(0%, -50%);
}
xxxxxxxxxx
//This is the js code. It is using jQuery 3.5.1
//You need to change the code a bit, but this is a good beginning.
// Get the img element with the sticky position
var stickyImg = $('#stickyImg');
// Get the div elements that contain the image URLs
var divs = $("div[data-src]");
// Create a flag variable to keep track of whether the img element has been faded out
var imgFadedOut = false;
// Add a scroll event listener to the window
$(window).on('scroll', function() {
// Loop through the div elements
for (var i = 0; i < divs.length; i++) {
// Use the eq() method to select the i-th element from the divs collection
var div = divs.eq(i);
// Calculate the position of the div relative to the viewport
var rect = div[0].getBoundingClientRect();
// Check if the div is in the middle of the viewport
if (rect.top >= 0 && rect.bottom <= window.innerHeight) {
// Get the image URL from the div's "data-src" attribute
var imgUrl = div.data('src');
// Check if the img element has already been faded out
if (!imgFadedOut) {
// Use the fadeOut() method to fade out the img element
stickyImg.fadeOut(function() {
// Set the src attribute of the sticky img element to the new image URL
stickyImg.attr('src', imgUrl);
// Use the fadeIn() method to fade in the img element with the new image
stickyImg.fadeIn(function() {
// Reset the imgFadedOut flag to false after the fade in animation is complete
imgFadedOut = false;
});
});
}
// Break out of the loop
break;
}
}
});
xxxxxxxxxx
<!-- This is the HTML code -->
<div class="container">
<div class="row">
<div class="col-6">
<div class="row" id="section">
<div class="col-6">
<div data-src="https://place-hold.it/500x500/green/white.jpg&text=Lorem%20Ipsum"></div>
<div>Some content for the first div</div>
</div>
</div>
<div class="row" id="section">
<div class="col-6">
<div data-src="https://place-hold.it/500x500/blue/white.jpg&text=Lorem%20Ipsum"></div>
<div>Some content for the first div</div>
</div>
</div>
<div class="row" id="section">
<div class="col-6">
<div data-src="https://place-hold.it/500x500/red/white.jpg&text=Lorem%20Ipsum"></div>
<div>Some content for the first div</div>
</div>
</div>
</div>
<div class="col-6 sticky__image">
<img id="stickyImg" src="https://place-hold.it/500x500/green/white.jpg&text=Lorem%20Ipsum">
</div>
</div>
</div>
<!-- Repeat the divs for each row... -->