[jQuery] check if scrolled

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

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?



This script should do what you want:

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

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

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