0

So I am trying to show a tooltip like box as I scroll my webpage and I would like it to follow the scrollbar along the right side of the page.

I looked around and found something to attempt to accomplish that as shown below:

function returnPercentHeight(){
    var a = document.getElementById('rightPanel').scrollTop;
    var b = document.getElementById('rightPanel').scrollHeight - document.getElementById('rightPanel').clientHeight;
    return ((a/b) * 100);
}

I then append a % to the end and set the top margin of the tooltip to that returned value. This works pretty well (sort of) I have to adjust the return((a/b) * x) part (x) to make it follow the scrollbar based on the size of the browser window. Is there a better way to accomplish what I am trying to do? (NOTE: I can only use javascript, no JQuery please.)

EDIT:

Only the div given an ID of 'RightPanel' is scrolling, I am not using the scrollbar on the browser, but a scrollbar on an inner div.

Jacob
  • 33
  • 1
  • 1
  • 5
  • 1
    http://stackoverflow.com/questions/2481350/retrieve-scrollbar-position-with-javascript – İsmet Alkan Jun 25 '14 at 13:02
  • http://stackoverflow.com/questions/11193453/find-the-vertical-position-of-scrollbar-without-jquery – İsmet Alkan Jun 25 '14 at 13:03
  • http://www.softcomplex.com/docs/get_window_size_and_scrollbar_position.html – İsmet Alkan Jun 25 '14 at 13:03
  • http://digitaldreamer.net/blog/2010/5/9/getting-browsers-scroll-position-javascript/ – İsmet Alkan Jun 25 '14 at 13:03
  • http://dropshado.ws/post/4214189829/getting-and-setting-scroll-position – İsmet Alkan Jun 25 '14 at 13:04
  • @IsmetAlkan please don't spam comments... – T J Jun 25 '14 at 13:24
  • So the actual answer, after exploring other options, the final result became: `function returnPercentHeight(){ var a = document.getElementById('rightPanel').scrollHeight; var b = document.getElementById('rightPanel').scrollTop + .5*document.getElementById('rightPanel').clientHeight; return ((b/a) * document.getElementById('rightPanel').clientHeight - 100); }` where 100 is the height of the div that is scrolling with the scrollbar – Jacob Jun 25 '14 at 15:25

2 Answers2

2

There are three ways to do so:

First:

is to use the fixed position as following;

Position: Fixed;

Second:

With jQuery;

$(function(){
   $(window).on('scroll', function() {
     var scrollPOS = $(document).scrollTop();
     $('.scroll').css({
        top: scrollPOS
     });
   }).scroll();
});

Third:

Same as the previous, only animated;

$(window).on('scroll', function() {
  $("#div").stop().animate({
     "marginTop": ($(window).scrollTop()) + "px", 
     "marginLeft":($(window).scrollLeft()) + "px"}, "slow" );
});
Explisam
  • 749
  • 13
  • 26
0

Although IE doesn't support, this is the coolest I've seen:

// get
var x = window.scrollX,
    y = window.scrollY;

// set
window.scrollTo(1, 2);
İsmet Alkan
  • 5,361
  • 3
  • 41
  • 64