Bryce Johnson
Bryce Johnson

Reputation: 6901

Connect a div's width to scrollTop() value with jQuery / javascript

I'm trying to make a scroll progress bar for a website. Basically, I want the width of a div (with a colored background) to be associated with how far the user has scrolled down.

I'm pretty new to jQuery--it's only my second project. Any ideas on how I could get it to work?

Here's my HTML:

<div class="scroll-progress"></div>

Here's the CSS:

.scroll-progress {
  width:10px; height:10px;
  background-color:green;
  position:fixed;
  top:0em;
  left:0em;
}

and the jQuery I took a hack at:

$(document).ready(function(){

  $(window).scroll(function(){

var docHeight = $(document).height();
var scrollDepth = $(window).scrollTop(); 
var scrollPercent = parseFloat(scrollDepth / docHeight) * 100;


  $(".scroll-progress").css(width,scrollPercent);


  });
});

Upvotes: 1

Views: 790

Answers (1)

user2869113
user2869113

Reputation:

I developed your project a little bit, check this out: (multiplicator is 103, and not 100, because of difference that the scrollbar height is causing itself)

http://jsfiddle.net/tdBfD/5/

$(document).ready(function(){
    $(window).scroll(function(){
        var docHeight = $(document).height();
        var ScrollTop = $(window).scrollTop();
        var NewWidth = (ScrollTop / docHeight) * 103
        $(".scroll-progress").width(NewWidth);
    });
});

Upvotes: 3

Related Questions