[jQuery] check if scrolled

var fromTop = 200;
	
	scrolled();
	$(window).scroll( function () {
	  	scrolled();
	});
	
	function scrolled () {
		if ( ( $(window).scrollTop() - $('#test').offset().top ) > fromTop ) {
	  		$('#test').addClass("fixed");
	  	} else {
	  		$('#test').removeClass("fixed");
	  	}
	}

I’m trying to add a class to #test when #test less than 200px from top of viewport. Otherwise, I’d like the class removed.

I’m not too far, but a) I get a pretty bad flickr (the “fixed” class seems to be added and removed like crazy) and b) I’m not sure that fromTop is really taken into account (but it’s hard to say because of a) )

Does anyone know how to fix the flickr problem and improve this code?

:slight_smile:

Hi,

This script should do what you want:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <style>
      .highlighted { background-color: blue; color: white;}
      .spacer{ height:500px;}
    </style>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
  </head>

  <body>
    <div class="spacer"></div>
    <p id="test">Watch me!</p>
    <div class="spacer"></div>
    <div class="spacer"></div>
    <script>
      $(document).scroll(function(){
        var el = $('#test');
        var top = $(el).offset().top - $(document).scrollTop();
        if (top < 200 && !el.is('.highlighted')){
          $(el).addClass('highlighted');
        }
        if (top > 200 && el.is('.highlighted')){
          $(el).removeClass('highlighted');
        }  
      });
    </script>
  </body>
</html>

As you can tell, if the element with the id #test is nearer than 200px to the top of the viewport, it has the class .highlighted added to it (as long as it doesn’t already have this class).
When it is more than 200px away from the top, the class is removed (as long as it existed in the first place).

Reference: http://stackoverflow.com/questions/5279055/detect-when-element-is-less-than-100px-from-top-of-window-change-css