3

I've got a javascript slideshow at the top of my page. When a slide changes to the next image, I call another function to change the background colour of the page.

The client wants the background colour to stop changing when the slideshow is no longer in view, i.e. when the user has scrolled down the page.

Is there any way to detect if an element is no longer visible due to scrolling?

demoncodemonkey
  • 11,730
  • 10
  • 61
  • 103
  • 2
    possible duplicate of [How to check if an element is really visible with javascript.](http://stackoverflow.com/questions/704758/how-to-check-if-an-element-is-really-visible-with-javascript) – David Tang Jun 08 '11 at 05:33
  • 1
    @Box9: That question asks for three pieces of information, of which scrolling is one, but there aren't any really good scrolling answers after two years and that question (unlike this one) says they use Prototype. So I'd say this should stand on its own. – T.J. Crowder Jun 08 '11 at 05:43

3 Answers3

4

Test code in jQuery

function test() {
    var $elem = $('.test');
    var visibleAtTop = $elem.offset().top + $elem.height() >= $(window).scrollTop();
    var visibleAtBottom = $elem.offset().top <= $(window).scrollTop() + $(window).height();
    if (visibleAtTop && visibleAtBottom) {
        alert('visible');
    } else {
        alert('invisible (at ' + (visibleAtTop ? 'bottom' : 'top') + ')');
    }
}

Full working example at http://jsfiddle.net/9PaQc/1/ (Updated: http://jsfiddle.net/9PaQc/2/ )

P.S. This only checks for vertical scroll. For horizontal, just do the same with top replaced with left, Y -> X and height() -> width()

EDIT

Made it all the way jQuery (to ensure x-browser compatibility) by changing window.scrollY -> $(window).scrollTop()

mkilmanas
  • 3,395
  • 17
  • 27
1

You can use the jQuery $.scrollTop function, probably from a scroll event handler to script this.

Tobias Cohen
  • 19,893
  • 7
  • 54
  • 51
0

Use the window.pageYOffset to determine scroll amount in window. Use current offset of the object to check if it is in view. Note that these values are mostly browser dependent, so first check if it exists then act on it.

Cem Kalyoncu
  • 14,120
  • 4
  • 40
  • 62