E-com DevBlog Spider-ball-vacuum

1Jun/100

Check Scroll Bar Position

I few weeks ago I was tasked with making one of those annoying "you must read the entire page before you continue" things (which as you know really just means you only need to scroll to the bottom of the page before continuing). It was something that I thought would be pretty easy to find on the web considering how often I run into it in use. However I was wrong, so here is what I was able to come up with.

?View Code JAVASCRIPT
$("#selector").scroll(function() {
   var elem = $(this);
   var position = elem[0].scrollHeight - elem.scrollTop();
   if(position == $(elem).outerHeight())
      $(":button:contains('submit')").removeAttr("disable");
   else
      $(":button:contains('submit')").attr("disable","disable");
});

A few things to note:
the "elem[0]" that defines "var position" is significant for some reason, I tried it without the "[0]" and it broke, I'm not 100% sure why so if anyone wants to weigh in, that would be great. Secondly, it is good to keep in mind that the "disable" attr is not supported on IE7 and lower so in order to fix band-aid this I simply made the button look disabled by doing something like.

?View Code JAVASCRIPT
if(position == $(elem).outerHeight())
     $(":button:contains('submit')").css("cursor","pointer");
else
     $(":button:contains('submit')").css("cursor","text");

Ultimately this only fakes people out if they pay attention to their cursor, which is probably less than 50% of the time. so really the best way to do this i found is as follows:

?View Code JAVASCRIPT
$("#selector").scroll(function() {
   var elem = $(this);
   if(checkScrollTop(elem))
      $(":button:contains('submit')").css("cursor","pointer");
   else
      $(":button:contains('submit')").css("cursor","text");
});

Then I Have a function called checkScrollTop() which takes an argument.

?View Code JAVASCRIPT
function checkScrollTop(elem) {
   var position = elem[0].scrollHeight - elem.scrollTop();
   if(position == $(elem).outerHeight()) {
      return true;
   }
   return false;
}

And last but definatley not least, a click event on the button so we can catch those trying to cheat w/ IE7 and (gulp) below.

?View Code JAVASCRIPT
$(":button:contains('submit')").click(function() {
   var elem = $("#selector");
   if(checkScrollTop(elem))
      $('#step1_disable').hide();
   else
      alert("Please read the entire policy before clicking \"submit\"");
});

to break it down, the $("#selector").scroll function simply decorates the button, while the click event on the button determines if the user can continue, if not it pops an alert up telling them what they must do. both events use the checkScrollTop(elem) function which measures the position of the scroll-bar.
Happy Annoying people :)

Print This Post Print This Post