Test when element is visible on screen

117 Views Asked by At

I'd like to test whether a certain div is visible on screen. Once it is visible, I'd like the divs around it to change background color.

Here is what I currently have: http://jsfiddle.net/4y9f2574/1/

if ($('.onscreen').isOnScreen()) {
    $('.box').css('background','green');
}

Any idea why the blue boxes aren't changing to green when the orange box is visible?

Thanks! Lauren

3

There are 3 best solutions below

0
On

There is nothing in your fiddle with class onscreen. Did you mean to write .box instead? Like:

if ($('.box').isOnScreen()) {
    $('.box').css('background-color','green');
}
0
On

there is no object with class onscreen

Is this you wanted? http://jsfiddle.net/ez8vmbL7/1/

0
On

You only run your if statement once when the page is loaded. If you want it to run when you scroll the window you can do like this:

$(window).scroll(function () {
    if ($('.onscreen').isOnScreen()) {
        $('.box').not('.onscreen').css('background','green');
    }
});

You also need to add onscreen to the orange box.

<div class="box orange onscreen"></div>

Check this jsfiddle