1
\$\begingroup\$

I've made this coding for large web pages with lots of text, images etc. If the user scrolls down or up it shows where the current view approximately is. In relation to the overall document height.

I'm considering to put it on GitHub. What improvements have be made so that it can be used as an Plugin, so that it can be used in different environments?

var progr = progr || {};
progr.display = document.querySelector('.display');

/**
 * Returns the current position within the HTML document. 
 * @return { string } The current position in relation to
 *  the overall document as percent.
 */
progr.getPercentageReached = function() {
  var dimensions = document.documentElement.getBoundingClientRect();
  var viewportHeight = document.documentElement.clientHeight;
  var heightLeft = Math.abs(Math.ceil(dimensions.bottom) - viewportHeight);
  
  return Math.ceil(((dimensions.height - heightLeft) * 100 / dimensions.height)) + '%';
}

// Make sure all images etc. are loaded. So that 
//  dimensions can be retrieved correct.
window.addEventListener('load', function() {
  progr.display.textContent = progr.getPercentageReached();

  window.addEventListener('scroll', function() {   
    progr.display.textContent = progr.getPercentageReached();
  });
});
* {
  padding: 0;
  margin: 0;
  border: 0;
}

html {
  overflow-y: scroll;
}

img {
  padding: 20px;
}

.wrapper {
  margin: 10px auto;
  width: 500px;
}

.display {
  position: fixed;
  background-color: #454545;
  color: #efefef;
  font-weight: 800;
  padding: 8px 10px;
  width: 55px;
  height: 20px;
  text-align: center;
  line-height: 20px;
  border-radius: 18px;
  font-size: 1.1rem;
  box-shadow: 4px 4px 6px grey;
  left: 65%;
  top: 2%;
  font-family: verdana, sans-serif;
  z-index: 1000;
  text-shadow: 0 1px 0 #cdcdcd, 0 1px 0 black;
}

.content {
  padding: 10px 30px;
  background-color: #efefef;
  border: 1px solid black;
}
<div class="wrapper">
  <div class="display"></div>
  <div class="content">
    <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor.
      Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur
      ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.
      Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec,
      vulputate eget, arcu.</p>
    <p>In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum
      felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum
      semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu,
      consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis,
      feugiat a, tellus.</p>
    <img src="https://placebear.com/350/300" alt="pic" />
    <p>Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet.
      Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui.
      Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper
      libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel,
      luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus.
      Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet
      orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh.
      Donec sodales sagittis magna. 
    </p>
    <p>Li Europan lingues es membres del sam familie. Lor separat existentie es un myth.
      Por scientie, musica, sport etc, litot Europa usa li sam vocabular. Li lingues
      differe solmen in li grammatica, li pronunciation e li plu commun vocabules.
      Omnicos directe al desirabilite de un nov lingua franca: On refusa continuar
      payar custosi traductores.</p>
    <img src="https://placebear.com/200/300" alt="pic" />
    <p>At solmen va esser necessi far uniform grammatica, pronunciation e plu sommun
      paroles. Ma quande lingues coalesce, li grammatica del resultant lingue es plu
      simplic e regulari quam ti del coalescent lingues. Li nov lingua franca va esser
      plu simplic e regulari quam li existent Europan lingues.</p>

    <p>It va esser tam simplic quam Occidental in fact, it va esser Occidental. A
      un Angleso it va semblar un simplificat Angles, quam un skeptic Cambridge amico
      dit me que Occidental es. Li Europan lingues es membres del sam familie. Lor
      separat existentie es un myth. Por scientie, musica, sport etc, litot Europa usa
      li sam vocabular. Li lingues differe solmen in li grammatica, li pronunciation
      e li plu commun vocabules. Omnicos directe al desirabilite de un nov lingua
      franca: On refusa continuar payar custosi traductores. At solmen va esser
      necessi far uniform grammatica, pronunciation e plu sommun paroles.</p>

    <p>Vestibulum purus quam, scelerisque ut, mollis sed, nonummy id, metus. Nullam
      accumsan lorem in dui. Cras ultricies mi eu turpis hendrerit fringilla.
      Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere
      cubilia Curae; In ac dui quis mi consectetuer lacinia. Nam pretium turpis et
      arcu. Duis arcu tortor, suscipit eget, imperdiet nec, imperdiet iaculis, ipsum.
      Sed aliquam ultrices mauris. Integer ante arcu, accumsan a, consectetuer eget,
      posuere ut, mauris. Praesent adipiscing. Phasellus ullamcorper ipsum rutrum
      nunc. Nunc nonummy metus. Vestibulum volutpat pretium libero. Cras id dui.
      Aenean ut eros et nisl sagittis vestibulum. Nullam nulla eros, ultricies
      sit amet, nonummy id, imperdiet feugiat, pede.</p>
    <p>Li Europan lingues es membres del sam familie. Lor separat existentie es un myth. Por scientie, musica, sport etc, litot Europa usa li sam vocabular. Li lingues differe solmen in li grammatica, li pronunciation e li plu commun vocabules. Omnicos directe al desirabilite de un nov lingua franca: On refusa continuar payar custosi traductores. At solmen va esser necessi far uniform grammatica, pronunciation e plu sommun paroles.</p>

<p>Ma quande lingues coalesce, li grammatica del resultant lingue es plu simplic e regulari quam ti del coalescent lingues. Li nov lingua franca va esser plu simplic e regulari quam li existent Europan lingues. It va esser tam simplic quam Occidental in fact, it va esser Occidental. A un Angleso it va semblar un simplificat Angles, quam un skeptic Cambridge amico dit me que Occidental es. Li Europan lingues es membres del sam familie. Lor separat existentie es un myth. Por scientie, musica, sport etc, litot Europa usa li sam vocabular. Li lingues differe solmen in li grammatica, li pronunciation e li plu commun vocabules. Omnicos directe al desirabilite de un nov lingua franca: On refusa continuar payar custosi traductores. At solmen va esser necessi far uniform grammatica, pronunciation e plu sommun paroles.</p>
<img src="https://placebear.com/400/300" alt="pic" />
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor.
      Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur
      ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.
      Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec,
      vulputate eget, arcu.</p>
  </div>
</div>

The uncompiled SASS-code. I've used variables so that the display can be easy to adjust.

$x: 65%;
$y: 2%;
$displayBackground: #454545;
$displayColor: #efefef;
$displayFontStack: verdana,
sans-serif;
$fontSize: 1.1rem;
$displayWidth: 55px;
$displayHeight: 20px;
$displayRadius: 18px;
$displayPadding: 8px 10px;
$displayBoxShadow: 4px 4px 6px grey;
$displayTextShadow: 0 1px 0 #cdcdcd,
0 1px 0 black;
$displayFontWeight: 800;
* {
  padding: 0;
  margin: 0;
  border: 0;
}

html {
  overflow-y: scroll;
}

img {
  padding: 20px;
}

.wrapper {
  margin: 10px auto;
  width: 500px;
}

.display {
  position: fixed;
  background-color: $displayBackground;
  color: $displayColor;
  font-weight: $displayFontWeight;
  padding: $displayPadding;
  width: $displayWidth;
  height: $displayHeight;
  text-align: center;
  line-height: $displayHeight;
  border-radius: $displayRadius;
  font-size: $fontSize;
  box-shadow: $displayBoxShadow;
  left: $x;
  top: $y;
  font-family: $displayFontStack;
  z-index: 1000;
  text-shadow: $displayTextShadow;
}

.content {
  padding: 10px 30px;
  background-color: #efefef;
  border: 1px solid black;
}

\$\endgroup\$
  • \$\begingroup\$ That was quick, don't rush to accept answers, you might get better answers in some time. \$\endgroup\$ – Tushar Aug 11 '16 at 10:19
  • \$\begingroup\$ Okay. Will do so the next time. Thanks for the tipp and answer. :) \$\endgroup\$ – michael.zech Aug 11 '16 at 10:20
2
\$\begingroup\$

Here are some improvements:

  1. Use IIFE.

    • This will make the variables defined inside it private thus avoid cluttering globals
    • Passing window and document objects will make it available in current scope and the scope chaining to find them will be reduced, improving performance slightly.
    • Allows to create private and public variables and methods.
  2. Customizations to the element showing the percentage scrolled
    • Accept a selector from user and use it to show the percentage. If no selector passed, use the default selector. If selector is passed, handle the condition that the element matching the selector does not exists in the DOM
    • Accept the styles as an object and apply those to the element
  3. Compute the dimensions only when required.
    • On initialization of the plugin, compute the dimensions
    • Update the dimensions when window is resized
  4. Provide options
    • To set the styles to the element showing percentage
    • To get the percentage, in case if user want to show this somewhere else on a particular condition.

var progr = (function(window, document, undefined) {
  'use strict';
  var viewportHeight = document.documentElement.clientHeight;

  var _el;
  var init = function(elSelector) {
      elSelector = elSelector || '#progr_display';
      _el = document.querySelector(elSelector);

      // If element does not exists, throw error
      if (_el === null) {
        throw 'Element ' + elSelector + ' does not exists';
      }

      _bindEvents();
    },
    getPercent = function() {
      var dimensions = document.documentElement.getBoundingClientRect();

      return Math.ceil(((dimensions.height - (Math.abs(Math.ceil(dimensions.bottom) - viewportHeight))) * 100 / dimensions.height)) + '%';
    },
    _updatePercent = function() {
      _el.textContent = getPercent();
    },
    /**
     * Bind 'load', 'scroll' and 'resize' events on window
     */
    _bindEvents = function() {
      // Bind Events on window
      window.addEventListener('load', _updatePercent);
      window.addEventListener('scroll', _updatePercent);

      var _timeout;
      // On resize, update the dimensions
      window.addEventListener('resize', function() {
        if (_timeout) {
          // Clear previous timeout
          clearTimeout(_timeout);
        }

        _timeout = setTimeout(function() {
          // Update dimensions
          viewportHeight = document.documentElement.clientHeight;

          // Update the scroll percentage
          _updatePercent();
        }, 250);
      });
    };

  return {
    init: init,
    getPercent: getPercent,
    updateStyles: function(stylesObj) {
      Object.assign(_el.style, stylesObj);
    }
  };
}(window, document));

// Usage
progr.init();

// For demo
setTimeout(function() {
  progr.updateStyles({
    background: 'green',
    color: 'gray'
  });
}, 5200);
* {
  padding: 0;
  margin: 0;
  border: 0;
}
html {
  overflow-y: scroll;
}
img {
  padding: 20px;
}
.wrapper {
  margin: 10px auto;
  width: 500px;
}
#progr_display {
  position: fixed;
  background-color: #454545;
  color: #efefef;
  font-weight: 800;
  padding: 8px 10px;
  width: 55px;
  height: 20px;
  text-align: center;
  line-height: 20px;
  border-radius: 18px;
  font-size: 1.1rem;
  box-shadow: 4px 4px 6px grey;
  left: 65%;
  top: 2%;
  font-family: verdana, sans-serif;
  z-index: 1000;
  text-shadow: 0 1px 0 #cdcdcd, 0 1px 0 black;
}
.content {
  padding: 10px 30px;
  background-color: #efefef;
  border: 1px solid black;
}
<div class="wrapper">
  <div id="progr_display"></div>
  <div class="content">
    <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium
      quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu.</p>
    <p>In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat
      vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus.</p>
    <img src="https://placebear.com/350/300" alt="pic" />
    <p>Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper
      libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci
      eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna.
    </p>
    <p>Li Europan lingues es membres del sam familie. Lor separat existentie es un myth. Por scientie, musica, sport etc, litot Europa usa li sam vocabular. Li lingues differe solmen in li grammatica, li pronunciation e li plu commun vocabules. Omnicos directe
      al desirabilite de un nov lingua franca: On refusa continuar payar custosi traductores.</p>
    <img src="https://placebear.com/200/300" alt="pic" />
    <p>At solmen va esser necessi far uniform grammatica, pronunciation e plu sommun paroles. Ma quande lingues coalesce, li grammatica del resultant lingue es plu simplic e regulari quam ti del coalescent lingues. Li nov lingua franca va esser plu simplic
      e regulari quam li existent Europan lingues.</p>

    <p>It va esser tam simplic quam Occidental in fact, it va esser Occidental. A un Angleso it va semblar un simplificat Angles, quam un skeptic Cambridge amico dit me que Occidental es. Li Europan lingues es membres del sam familie. Lor separat existentie
      es un myth. Por scientie, musica, sport etc, litot Europa usa li sam vocabular. Li lingues differe solmen in li grammatica, li pronunciation e li plu commun vocabules. Omnicos directe al desirabilite de un nov lingua franca: On refusa continuar
      payar custosi traductores. At solmen va esser necessi far uniform grammatica, pronunciation e plu sommun paroles.</p>

    <p>Vestibulum purus quam, scelerisque ut, mollis sed, nonummy id, metus. Nullam accumsan lorem in dui. Cras ultricies mi eu turpis hendrerit fringilla. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; In ac dui
      quis mi consectetuer lacinia. Nam pretium turpis et arcu. Duis arcu tortor, suscipit eget, imperdiet nec, imperdiet iaculis, ipsum. Sed aliquam ultrices mauris. Integer ante arcu, accumsan a, consectetuer eget, posuere ut, mauris. Praesent adipiscing.
      Phasellus ullamcorper ipsum rutrum nunc. Nunc nonummy metus. Vestibulum volutpat pretium libero. Cras id dui. Aenean ut eros et nisl sagittis vestibulum. Nullam nulla eros, ultricies sit amet, nonummy id, imperdiet feugiat, pede.</p>
    <p>Li Europan lingues es membres del sam familie. Lor separat existentie es un myth. Por scientie, musica, sport etc, litot Europa usa li sam vocabular. Li lingues differe solmen in li grammatica, li pronunciation e li plu commun vocabules. Omnicos directe
      al desirabilite de un nov lingua franca: On refusa continuar payar custosi traductores. At solmen va esser necessi far uniform grammatica, pronunciation e plu sommun paroles.</p>

    <p>Ma quande lingues coalesce, li grammatica del resultant lingue es plu simplic e regulari quam ti del coalescent lingues. Li nov lingua franca va esser plu simplic e regulari quam li existent Europan lingues. It va esser tam simplic quam Occidental
      in fact, it va esser Occidental. A un Angleso it va semblar un simplificat Angles, quam un skeptic Cambridge amico dit me que Occidental es. Li Europan lingues es membres del sam familie. Lor separat existentie es un myth. Por scientie, musica,
      sport etc, litot Europa usa li sam vocabular. Li lingues differe solmen in li grammatica, li pronunciation e li plu commun vocabules. Omnicos directe al desirabilite de un nov lingua franca: On refusa continuar payar custosi traductores. At solmen
      va esser necessi far uniform grammatica, pronunciation e plu sommun paroles.</p>
    <img src="https://placebear.com/400/300" alt="pic" />
    <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium
      quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu.</p>
  </div>
</div>

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.