A
A
Anastasia2021-07-12 10:54:49
JavaScript
Anastasia, 2021-07-12 10:54:49

How to add a class when pages are updated?

I have a header on my site, and when I scroll down the page, it hides. And when scrolling the page up, I show it.

$(function () {
  var lastScrollTop = 0,
    delta = 15;
  $(window).scroll(function (event) {
    var st = $(this).scrollTop();
    if ($(window).scrollTop() > 50) {
      $("header").addClass("active");
    } else {
      $("header").removeClass("active");
    }
    if (Math.abs(lastScrollTop - st) <= delta) return;
    if (st > lastScrollTop && lastScrollTop > 0) {
      $("header").css("top", "-146px");
    } else {
      $("header").css("top", "0px");
    }
    lastScrollTop = st;
  });
});


header {
    width: 100%;
    position: fixed;
    top: 0;
    transition: .5s;
    z-index: 99;
}

header.active {
    background-color: #fff;
    box-shadow: rgb(0 0 0 / 4%) 0px 4px 4px;
}


But if, for example, I scroll to half the page and refresh the site, then my header will be without the .active
class .

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Sokolov, 2021-07-12
@patsooo

function which inside $(window).scroll()declare above. And call 1 more time explicitly, not by event.

spoiler
$(function () {
  function onScroll(event) {
    var st = $(this).scrollTop();
    if ($(window).scrollTop() > 50) {
      $("header").addClass("active");
    } else {
      $("header").removeClass("active");
    }
    if (Math.abs(lastScrollTop - st) <= delta) return;
    if (st > lastScrollTop && lastScrollTop > 0) {
      $("header").css("top", "-146px");
    } else {
      $("header").css("top", "0px");
    }
    lastScrollTop = st;
  }

  var lastScrollTop = 0,
    delta = 15;
  $(window).scroll(onScroll);

  onScroll();
});

V
v3shin, 2021-07-12
@v3shin

$(window).scroll(
   // bla-bla-bla
).scroll();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question