1
\$\begingroup\$

The idea is the following:

I have a large text with a header upon it and a navigation bar. The navigation bar is located between header and text.

If the user scrolls downwards then the header-part moves out of the browser window. The navigation bar moves upwards too. But just in the beginning. When its top reaches the upper border of the browser window it becomes attached and stays in that position.

When the user scrolls upward again then it finally becomes detached again, so that the moves gradually back to its former position.

I've added some additional thoughts concerning my implementation as comments.

(function() {
  'use strict';

  var bar = document.querySelector('.bar');
  var barDimensions = bar.getBoundingClientRect();
  const DELTA_BAR_TO_TOP = barDimensions.top;

  window.addEventListener('scroll', function() {
    var docDimensions = document.body.getBoundingClientRect();

    barDimensions = bar.getBoundingClientRect();

    // First condition: As soon as the nav-bar touches the
    //  top it becomes attached.
    // Second condition: (document.top + 'former margin
    //  to top of document') has to be a negative
    //  number.
    // When scrolling BACK upwards: (document-top + 'former margin')
    //  has become >= 0 again (from being a negative number before).
    //  Now the second condition makes sure that the else-branch
    //  is entered. Result: Nav-bar becomes moveable again.

    if (barDimensions.top <= 0 && (docDimensions.top + DELTA_BAR_TO_TOP) < 0) {
      bar.style['position'] = 'fixed';
      bar.style['top'] = '0';
    } else {
      bar.style['position'] = 'static';
    }
  });
})();
* {
  margin: 0;
  padding: 0;
  border: 0;
}
body {
  background-color: azure;
  font-size: 18px;
  font-family: georgia;
}
.wrap {
  margin: 30px auto;
  width: 100%;
  max-width: 1000px;
}
h1 {
  text-transform: uppercase;
}
.bar {
  height: 140px;
  width: 1000px;
  background: linear-gradient(#404040 20%, grey 40%, transparent);
  border-radius: 12px;
}
header {
  text-align: center;
  padding: 20px 0 50px;
}
header p {
  font-size: 1.5rem;
  margin-bottom: 1rem;
}
header p:nth-of-type(2) {
  font-size: 1.2rem;
}
main {
  padding: 30px 20px 0;
}
main p {
  margin-bottom: 20px;
}
.bar ul {
  list-style: none;
  display: flex;
  justify-content: space-around;
  height: 100%;
  align-items: center;
}
.bar ul li {
  display: block;
  float: left;
}
.bar ul li a {
  text-decoration: none;
  text-transform: uppercase;
  font-weight: 900;
  color: azure;
  font-size: 1.6rem;
  font-family: "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Geneva, Verdana, sans-serif;
}
.bar ul li a:hover {
  color: rgba(180, 0, 0, 0.4);
  cursor: crosshair;
}
<div class="wrap">
  <header>
    <h1>The main headline</h1>
    <p><strong>Li Europan lingues es membres del sam familie.</strong>
    </p>
    <p>Phasellus nec sem in justo pellentesque facilisis. Etiam imperdiet imperdiet orci. Nunc nec neque. Phasellus leo dolor, tempus non, auctor et, hendrerit quis, nisi. Curabitur ligula sapien, tincidunt non, euismod vitae, posuere imperdiet, leo. Maecenas
      malesuada. Praesent congue erat at massa. Sed cursus turpis vitae tortor. Donec posuere vulputate arcu. Phasellus accumsan cursus velit.</p>
  </header>
  <div class="bar">
    <ul>
      <li><a href="#" class="nav-hyperlink">First hyperlink</a>
      </li>
      <li><a href="#" class="nav-hyperlink">Second hyperlink</a>
      </li>
      <li><a href="#" class="nav-hyperlink">Third hyperlink</a>
      </li>
    </ul>
  </div>

  <main>
    <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>

    <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>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>

    <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>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>

    <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>Sed lectus. Donec mollis hendrerit risus. Phasellus nec sem in justo pellentesque facilisis. Etiam imperdiet imperdiet orci. Nunc nec neque. Phasellus leo dolor, tempus non, auctor et, hendrerit quis, nisi. Curabitur ligula sapien, tincidunt non,
      euismod vitae, posuere imperdiet, leo. Maecenas malesuada. Praesent congue erat at massa. Sed cursus turpis vitae tortor. Donec posuere vulputate arcu. Phasellus accumsan cursus velit. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices
      posuere cubilia Curae; Sed aliquam, nisi quis porttitor congue, elit erat euismod orci, ac placerat dolor lectus quis orci. Phasellus consectetuer vestibulum elit. Aenean tellus metus, bibendum sed, posuere ac, mattis non, nunc. Vestibulum fringilla
      pede sit amet augue. In turpis. Pellentesque posuere. Praesent turpis. Aenean posuere, tortor sed cursus feugiat, nunc augue blandit nunc, eu sollicitudin urna dolor sagittis lacus. Donec elit libero, sodales nec, volutpat a, suscipit non, turpis.
      Nullam sagittis. Suspendisse pulvinar, augue ac venenatis condimentum, sem libero volutpat nibh, nec pellentesque velit pede quis nunc. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Fusce id purus. Ut varius
      tincidunt libero. Phasellus dolor. Maecenas vestibulum mollis.</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>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.</p>

    <p>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. 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. 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>
  </main>
</div>

Have I chosen the right approach? Is everything done in a good manner? Or do I have to improve something?

Live demo also on CodePen (in case "Run code snippet" shouldn't work).

\$\endgroup\$
3
  • \$\begingroup\$ It would be nice if we can see this working visually. Ctrl M all your codes. \$\endgroup\$ – Tolani Nov 20 '16 at 13:19
  • \$\begingroup\$ @Tolani I'm pleased by your interest. :) Does the "Run code snippet" not work on your computer? I've tested it after writing the question and the seemed all well here (Mac with Chrome). ? ? ? Anyway: I've added a hyperlink to CodePen at the bottom. As an alternative ... \$\endgroup\$ – michael.zech Nov 20 '16 at 14:10
  • \$\begingroup\$ Perhaps because I used ES6 const in there? I've enabled "Babel JS" transpiler. Perhaps that helps. So that it becomes visible. \$\endgroup\$ – michael.zech Nov 20 '16 at 14:14
1
\$\begingroup\$

First, your JS.

I would suggest moving the styles that are on the JS into the CSS, and only have JS toggle classes containing those styles. The usual separation of concerns reasoning, as well as to have all the styling of your UI at different states be defined in one place, your CSS.

Your box logic is a bit off. Your nav scrolls past the top by about 10-20px before "jumping" into the fixed position. There's 2 problems. First one is your delta expression that appears to be used to remove the bar from its fixed state. The other is the content jump caused by the removal of the bar from the layout when fixed is applied.

Now over to your CSS.

Using the * should be avoided. I am pretty sure you want to remove default spacings. However, this will not play well with elements that expect default styling to be present. For instance, if ever content from a wysiwyg editor is placed on the page expecting default spacings for <p> and <hN> elements.

I would also suggest avoiding styling by element names. The problem with styling element names is that you can be styling elements you don't own. Again, the third-party content case. Suggesting you use classes to style to ensure you're only affecting your elements.

Speaking of class names, I would also suggest making your class names more specific. Names like "wrap" and "bar" are very generic names that can be used elsewhere. If you've ever used Bootstrap, you'll find that names like "btn" and "alert" are already used by the framework.

The JS piece can be simplified into:

var bar = document.querySelector('.bar');
var barPosition = bar.getBoundingClientRect();

window.addEventListener('scroll', function() {

  if (document.body.scrollTop > barPosition.top) {
    // Add class to bar to make it fixed
  } else {
    // Remove class from bar to make it flow
  }
});
\$\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.