I have a div in which there will be several images. I would like the images to disappear when the user scrolls to the point where the top or bottom edges of the image will already be hidden by the parent div. the structure is as follows:
<div class="parent"> <img/> <img/> </div>
My goal is to fade out the image when its top or bottom edge starts to be hidden by the parent div, and then it disappears when it scrolls to the full view.
I am using jQuery and listening to the div scroll event to check img offset().top , and as soon as it hits the top value that is not showing, I hide the image.
But this seems to take a lot of CPU time, since I have to iterate over the images with each scroll event. Also, although I call hide() on img , it doesn't hide it at all (put a breakpoint just to make sure it's called, and that was). Is there any way to do this?
EDIT: Thanks to mcpDESIGNS, I needed to use position() instead of offset() . Also, it seems that hide() not working as display set to none . So I switched to visibility:hidden and it works as expected.
EDIT2: As a note, here is the js I'm using, pretty much what mcpDesigns 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")