SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Zealot
    Join Date
    Jul 2011
    Posts
    199
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    [jQuery] check if scrolled

    Code JavaScript:
    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?


  2. #2
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,876
    Mentioned
    208 Post(s)
    Tagged
    12 Thread(s)
    Hi,

    This script should do what you want:

    HTML Code:
    <!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/5...dow-change-css


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •