I have a div that will have a few images in it. I would like for the images to disappear when the user scrolls to the point where the top or bottom edges of the image are just about to be hidden by the parent div. The structure is like this:
<div class="parent">
<img/>
<img/>
</div>
My goal is to have the image fade out when its top or bottom edges start to be hidden by the parent div, and then have it fade back in when its scrolled in to full view.
I am using jQuery and listening to the div scroll event to check the img offset().top, and once it hits a top value that is not in view, I hide the image.
But this seems to take up a lot of CPU time since I have to iterate through the images with each scroll event. On top of that, even though I call hide() on the img, it doesn’t hide it at all (put a break point in just to make sure it was getting called, and it was). Is there an accurate way to do this?
EDIT: Thanks to mcpDESIGNS, I was needed to use position() instead of offset(). Also, it looks like hide() wont work since display is set to none. So I switched to visibility:hidden and it works as expected.
EDIT2: Just as a note, here is the js I am using, pretty much what mcpDesigns had suggested
old
var display = $("div");
display.scroll(function () {
var avatars = $("div > img");
console.log("************************");
avatars.each(function (index) {
console.log($(this).offset().top);
if ($(this).offset().top < 40)
$(this).hide();
else {
$(this).show();
}
});
});
new
var display = $("div");
display.scroll(function () {
var avatars = $("div > img");
console.log("************************");
avatars.each(function (index) {
console.log($(this).position().top);
if ($(this).position().top < 0)
$(this).css("visibility", "hidden")//.hide();
else {
$(this).css("visibility", "")//.show();
}
});
});
You’ll need to do a lot of calculations based on each image and whether it’s position is either negative (meaning top of the parent scrollable div), or the same # as the height of your scrollable div.
Play around with that, but that’s basically the jist of it.