Friday, January 20, 2012

Detect where the scroll bar is with JQuery and provide visual cue to the user

I have a web page with a "display: fixed; z-index: 1; background: white" header at the top of the page. When I scroll down the body of my page slides behind the header. It works well but there is a problem:

  • There is no indicator aside from the scroll bar that the page is not at the TOP and it is deceiving.
To fix this I decided to use some simple JQuery watch for when the page is not scrolled at the top and to shade the background of the header slightly.


$(document).ready( function(){
  $(documnet).scroll( function(){
    var scrollPosition = $(document).scrollTop();
    if (scrollPosition == "0"){
      //The page is scrolled to the top
      $('#header').css('background', 'white');
    }
    else {
      //The page is not at the top
      $('#header').css('background', 'gray');
    }
  });
});



The code fires whenever the page is scrolled and checks if it is at the top. If it is at the top, it sets the header background to white. If it isn't at the top it sets it to gray and is a good visual cue to visitors that they are not at the top of the page.

A popular on is to display a hidden div in a fixed position near the edge of the screen with the text "Scroll back to top". When that div is visible the page is obviously not at the top, and when it is clicked, it is expected to take you back up to the top.

Here is some sample code for the click event to that takes the screen back to the top:

$(document).ready( function(){
  $("#scrollmessagediv").click( function(){
    //scroll to the top of the page
    $(document).scrollTop(0);
    //hide the element since we are at the top now
    $(this).hide();
  });
});


There are lot of ways to get creative with scrolling and JQuery, hopefully this got you started!

2 comments: