[Vuejs]-Hide navbar when scrolling, but do it so that it's not animated but naturally 'scrolled away'

3👍

I hope I didn’t get things wrong but if you want the bar to hide when you scroll, why not just position: absolute it and leave the normal scrolling make it disappear ? that might sound trivial but if you want a natural disappearance, that might be it, no ?

0👍

You can use CSS transitions on top to animate it back and forth. However you are triggering the hide when you scroll, you can add/remove classes to trigger the change.

👤Morfie

0👍

Set the position of the navbar a fixed (or whatever you have currently) until a scroll event on the window passes a certain point, then make the navbar relative to the scrolling container.

See this example: https://jsfiddle.net/n97tu7nt/

The HTML

<div id="main-container">
  <div class="nav" id="nav" style="position:fixed; height: 100px; background-color: blue; color: white; width:100%;">
    This is the Nav Bar <span id="pos"></span>
  </div>
  <div style="position:relative; top:130px;" id="container">
    <p>
      This is some text
    </p>
  ...

The Javascript

var c = document.getElementById('nav');
var t = document.getElementById('container');
var p = document.getElementById('pos');

p.innerHTML = window.scrollY;

var last_known_scroll_position = 0;
var ticking = false;

function doSomething(scroll_pos) {

  p.innerHTML = scroll_pos;
  if (scroll_pos > 100) {
    c.style.position = 'relative';
    t.style.top = 0;
  }
}

// From https://developer.mozilla.org/en-US/docs/Web/Events/scroll
window.addEventListener('scroll', function(e) {

  last_known_scroll_position = window.scrollY;

  if (!ticking) {

    window.requestAnimationFrame(function() {
      doSomething(last_known_scroll_position);
      ticking = false;
    });

    ticking = true;

  }

});

It is very hacky, but shows the principle.

👤Phil

Leave a comment