1

i want to add width to my div by the how much page height is so it can show how much page is left if page scrolled to bottom div width should be 100% and if it at middle it should be half

window.onscroll = function () {
    addLoaderWidth();
}

function addLoaderWidth() {
    var addWidth = window.pageYOffset;
    document.getElementById('load').style.width = addWidth + 'px';

}
Naveen Kashyap
  • 87
  • 1
  • 1
  • 11

2 Answers2

2

Your javascript works just fine. I had to add some style for the #load element, and add a container around the element that was scrollable. But it seems to work as expected:

window.onscroll = function () {
    addLoaderWidth();
}

function addLoaderWidth() {
    var addWidth = window.pageYOffset;
    document.getElementById('load').style.width = addWidth + 'px';

}
#load {
  height: 10px;
  width: 0px;
  background-color: blue;
  position: fixed;
  top: 0;
  left: 0;
  transition: all .2s ease;
}

.container {
  height: 1000px;
  position: relative;
}
<div class="container">
  <div id="load"></div>
</div>
mmshr
  • 937
  • 1
  • 7
  • 9
1

You can do this by calculating the percentage that was scrolled down and use that value as the width of the element.

const progress = document.getElementById('progress');
window.addEventListener('scroll', function() {
  let d = document.documentElement, b = document.body;
  let percentage = (d.scrollTop||b.scrollTop) / ((d.scrollHeight||b.scrollHeight) - d.clientHeight) * 100;
  progress.style.width = percentage + '%';
});
#progress {
  position: fixed;
  top: 0;
  left: 0;
  height: 8px;
  width: 0%;
  background-color: #48E;
}
#content {
  height: 2000px;
}
<div id="progress"></div>
<div id="content"></div>
Jan
  • 2,853
  • 2
  • 21
  • 26
  • whats the difference between scroll height and client height – Naveen Kashyap Jun 07 '19 at 07:35
  • Here are some good write-ups about the differences: [What is offsetHeight, clientHeight, scrollHeight?](https://stackoverflow.com/q/22675126/1970822)(SO) or [Difference between offsetHeight, clientHeight and scrollHeight](https://medium.com/@jbbpatel94/difference-between-offsetheight-clientheight-and-scrollheight-cfea5c196937)(Ext) – Jan Jun 07 '19 at 09:49