0

I have a div on my page, and I would like the background color to change when the viewer scrolls down to it.

How can I do this?

flyingfisch
  • 488
  • 1
  • 5
  • 16
  • Possible duplicate of [Check if element is visible after scrolling](http://stackoverflow.com/questions/487073/check-if-element-is-visible-after-scrolling). – Chris Nov 11 '14 at 23:53

2 Answers2

1

The commenter above is right. You should try something first and when you get stuck, the community will help you get unstuck. That said, here's a quick jquery to solve your problem.

$(document).ready(function(){
    var offsetTop = $('#test').offset().top, //offset from top of element - element has id of 'test'
        finalOffset = offsetTop - document.documentElement.clientHeight; //screen size
    $(window).on('scroll',function(){
        var whereAmI = $(document).scrollTop();
        if(whereAmI >= offsetTop){
            console.log("i've arrived at the destination");
        }
    })
})

Note that the above code executes the console.log() at every point past your requirement (meaning from there downwards). In case you want the execution to happen only one, you need to adapt the code a bit. One more note - if you're checking this in a fiddle, this document.documentElement.clientHeight needs to be adapted to work in an iframe. So test it on your local machine.

Radu Andrei
  • 1,032
  • 9
  • 18
1

I would have used CSS3 with something like this...

var elemTop = $('div').offset().top;
  $(window).scroll(function() {
     if($(this).scrollTop() == elemTop) {
       $('div').removeClass('hidden');
   }
});
Bryce Snyder
  • 353
  • 2
  • 7
  • 24