Fixed pop-up navigation for the website JQUERY, CSS. Instructions and examples

In this article, we will show you how to make the site header appear when you scroll up the page, but at the same time hide when you scroll down the page, so as not to block our view of the page itself.

In this article, we will show you how to make the site header appear when you scroll up the page, but at the same time hide when you scroll down the page, so as not to block our view of the page itself.

Watch DEMO        Download example

Preparing for work

First we need a header and some content for the scroll to appear . To do this, we will write HTML and CSS code for a primitive page.

HTML:

<!DOCTYPE html>
<html lang="ru">
  <head>
   <meta charset="UTF-8">
   <title>Шапочное волшебство</title>
   <link rel="stylesheet" href="/style.css">
  </head>
  <body>
    <header>
      <div class="container">
        <nav>
          <ul>
            <li><a href="#">О компании</a></li>
            <li><a href="#">Наша деятельность</a></li>
            <li><a href="#">Контакты</a></li>
           </ul>
         </nav>
      </div>
    </header>
    <main>
      <h1>Контент</h1>
    </main>
  </body>
</html>

CSS:

body, h1 {
    margin: 0;
    padding: 0;
    border: 0;
    outline: 0;
    font-weight: normal;
    font-style: normal;
    vertical-align: baseline;
}
.container {
    width: 970px;
    margin: 0 auto;
    padding: 0 15px;
    display: block;
    position: relative;
}
header {
    background: orange;
}
header ul {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
body {
    background: grey;
    height: 150vh;
}

Styles for implementing a task

Now we can begin our main task, namely writing the code to move the header. And we will start by writing styles, and then move on to writing JS code using the JQuery library.

First, let's write styles for the header itself:

header {
	position: fixed;
	left: 0;
	top: 0;
    	background: orange;
	width: 100%;
	-webkit-transition: top 0.4s;
	-moz-transition: top 0.4s;
	-o-transition: top 0.4s;
	transition: top 0.4s;
}

Here we have given the header a fixed position and positioned it relative to the left and top edge of the parent element. We set its width and enabled cross-browser displacement animation using the “ top ” property. But since we set the header to a fixed position, it fell out of the general flow, and the rest of the page pressed up (drove under the header). To do this, the page body needs to add an indent corresponding to the height of the header, in our case it is 50 pixels:

body {
    padding-top: 50px;
}

Next, let's set the styles so that the header moves up when scrolling down the page:

.fixed-header header {
	top: -50px;
}

And returned back when scrolling – up:

.fixed-header .show {
	top: 0;
}

This completes the styling of our page. But if we refresh the page, we see that nothing happens. Why? The thing is that our HTML document does not have the “ fixed-header ” and “ show ” classes that we wrote into the CSS document earlier. But simply adding classes will not help us realize our task. We need these classes to be created and deleted upon certain events, for this we need JavaScript, which we talked about earlier

Connecting scripts

To implement this step of our task, we need to connect the standard JQuery library, in our case it is version 3.3.1. JQuery is a wonderful JavaScript Framework that impresses with its ease of understanding and ease of use. To begin with, you will need the framework itself; you can download it on the official JQuery website. Then it needs to be connected next to the CSS file connection in the following way:

<script src="/js/jquery-3.3.1.min.js"></script>

Next, let's move on to writing the code itself by inserting the “ script ” tag. As a rule, scripts are inserted at the end of the site body or after the selector in which they are used:

<script type="text/javascript">
$(document).ready(function(){ //Вызов функции по загрузке интерфейса
  var tempScrollTop, currentScrollTop = $(window).scrollTop(); //объявление переменных и присвоение им значений
  $(window).scroll(function(){ //Вызов функции при прокрутке страницы
    currentScrollTop = $(window).scrollTop(); //присвоение переменной нового значения
      if (currentScrollTop > $('header').height()) { //Проверка условия 'переменная больше высоты шапки'
        $('body').addClass('fixed-header'); // создание класса 'fixed-header' в селекторе 'body'
        if ( tempScrollTop > currentScrollTop ) { //Проверка условия 'значение переменной до вызова функции больше значения после её вызова'
          $('header').addClass('show'); //создание класса 'show' в селекторе 'header'
        } else { // выполнение, если второе условие не прошло проверку
          $('header').removeClass('show'); //удаление класса 'show' в селекторе 'header'
        }
      } else { // выполнение, если первое условие не прошло проверку
        $('body').removeClass('fixed-header'); // удаление класса 'fixed-header' в селекторе 'body'
        $('header').removeClass('show'); //удаление класса 'show' в селекторе 'header'
      }
        tempScrollTop = currentScrollTop; //присвоение одной переменной значение другой
  });
});
</script>

In this code, we use the Jquery library method " .ready " which executes the function once the DOM (interface) has fully loaded. Next we will add the very function that should be executed by the method. In this function we declare variables and assign them a value, which is returned to us by the .scrollTop method , .ScrollTop - gets / sets the scroll top indent value.

The “ tempScrollTop” variable takes its value before the function is triggered by the “ .scroll ” method, and the “ currentScrollTop ” variable takes its value after. After that, we add a function that will be called by the “ .scroll ” method. The " scroll " event is sent when the scroll position of an element changes, regardless of the reason, whether the mouse is clicking on the scroll bar, or dragging the scroll bar, dragging inside the element, pressing arrow keys, or moving with the mouse wheel.

Next, we fill this function with code in which we set the currentScrollTop variable to a new value obtained by the .scrollTop() method we are already familiar with . On the next line, we set the condition that if the currentScrollTop variable is greater than the height of the header  selector (obtained using the .height() method ) increased by 5 pixels, then lines of code from 3 to 8 are executed (Specifically, using the .addClass method , we create a class for the body selector , after which another condition is checked, which says “if the tempScrollTop variable is greater than the currentScrollTop variable,” then the show class is created in the header selector using the .addClass method; if this condition does not pass, then the show class is removed from the header selector using the .removeClass method ). Otherwise, lines 10 and 11 are executed (which, using the .removeClass method, remove the fixed-header class from the body selector , and the show class from the header selector ). And after these conditions are met, at the end of the function we add the line: tempScrollTop = currentScrollTop ;, which assigns the value of the currentScrollTop variable to the tempScrollTop variable . This is necessary in order to save the value of the tempScrollTop variable for each subsequent execution of the function by the .scroll method .

As a result, our script takes the form provided above and performs all the actions we need.