I am trying to achieve a fixed image effect when it appears on the screen during scrolling, but I want it to return to its normal position if the user scrolls back up. The issue I'm facing is that when I use a JavaScript function to change the image position to fixed during scroll, it suddenly jumps or resizes, and I'm not sure why. My current workaround involves creating variables to adjust the width and left values of the image after fixing it, but this solution seems to be unique for each image on the page. I'm struggling to understand the underlying concept causing this problem. Simply resetting the width and left values to their original state does not seem to work. Does a fixed position resize an image?
Here is a jsfiddle showcasing the issue along with the code snippet below:
var sitckyImageWidth = "38.4%";
var normalImageWidth = "48%";
document.addEventListener("scroll", function(){
var windowTop = $(window).scrollTop();
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
//loop through each div and grab top/bottom/midpoint info and find id
$('.articles').each(function(i){
var top = $(this).offset().top;
var bottom = top+ $(this).height();
var midPoint = (bottom+top)/2;
var thisId = this.id;
var newId;
//use container div info to find media info
var newId = thisId+"Media";
var sectionImage=document.getElementById(newId);
var sectionImageTop = $(sectionImage).offset().top;
//if article is on the page, change position to fixed and set top position
if (top<=windowTop&&bottom>windowTop){
$(sectionImage).css("top","10px")
$(sectionImage).css("position","fixed")
//$(sectionImage).css("width",sitckyImageWidth)
}
//if container is not at top of the page, return to relative
if (bottom<=windowTop||(bottom>windowTop&&top>windowTop)){
$(sectionImage).css("position","relative")
}
})
}); //end scroll