7

I need to run some JavaScript when a div is visible in the browser window, for example, when it is scrolled to, even repeatedly. How would I go about doing so?

Basic structure:

<div class='page1'></div>

<div class='page2'></div>

<div class='page3'></div>

<div class='page4'></div>

CSS:

div {
    float: left;
    height: 500px;
    width: 500px;
    margin: 50px 0;
    background: grey;
}

Fiddle: http://jsfiddle.net/Q5BUe/1/

Shaz
  • 15,637
  • 3
  • 41
  • 59
test
  • 2,429
  • 15
  • 44
  • 81
  • get position of div, scrolled position of the window, window height and calculate whether or not it is within the boundaries. – Kuro Sep 07 '12 at 17:47
  • Possible duplicate of http://stackoverflow.com/questions/10555998/change-css-element-with-jquery-when-scroll-reaches-an-anchor-point – theunraveler Sep 07 '12 at 17:48

2 Answers2

12

As with the other provided question/solution, here is the full implementation...

Upon loading, we run the function to assign the visible divs with the corresponding color. On jQuery scroll handler, we continue to call the function to assign the new background color.

http://jsfiddle.net/Q5BUe/5/

$(allInView);
$(window).scroll(allInView);


function isScrolledIntoView(elem) {
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}

function allInView() {

    if (isScrolledIntoView($(".page1"))) $(".page1").css("backgroundColor", "red");
    else $(".page1").css("backgroundColor", "grey");

    if (isScrolledIntoView($(".page2"))) $(".page2").css("backgroundColor", "green");
    else $(".page2").css("backgroundColor", "#333");

    if (isScrolledIntoView($(".page3"))) $(".page3").css("backgroundColor", "yellow");
    else $(".page3").css("backgroundColor", "#222");

    if (isScrolledIntoView($(".page4"))) $(".page4").css("backgroundColor", "blue");
    else $(".page4").css("backgroundColor", "#111");

}
r0m4n
  • 3,474
  • 3
  • 34
  • 43
5

Since your implying your using jQuery you could be like

if($('#element').is(':visible'))
{
    //do your thing
}
chris
  • 36,115
  • 52
  • 143
  • 252