Hello, how can you use jquery when scrolling to determine if the image has fallen into sight, then show () it, if it went out of sight then hide ()?

  • one
    Basic Visibility Detection But I just can’t understand why I’m hiding something that isn’t visible? - Sergey Gornostaev
  • @SergeyGornostaev so that it does not load from the server. - Qwertiy
  • It will not help. - Sergey Gornostaev
  • @SergeyGornostaev, well, I think in this case, this is a general question about the dynamics of objects on the page, so that when scrolling the page everything moves, as is fashionable now :) - check1st

1 answer 1

You specify the following function, which takes a selector as the first argument and a boolean value to select visible (true) or invisible (false) elements:

function inWindow(s, v) { var scrollTop = $(window).scrollTop(); var windowHeight = $(window).height(); var currentEls = $(s); var resultVis = []; var resultInv = []; currentEls.each(function(){ var el = $(this); var offset = el.offset(); if (scrollTop <= offset.top && (el.height() + offset.top) < (scrollTop + windowHeight)) resultVis.push(this); else resultInv.push(this); }); if (v) return $(resultVis); else return $(resultInv); } 

Then, at the right moment you call, for example, when scrolling:

 $(window).scroll(function() { var imagesVisible = inWindow("img.myimage", true); var imagesInvisible = inWindow("img.myimage", false); imagesVisible.fadeIn(); imagesInvisible.fadeOut(); });