G
G
godsplane2020-04-23 16:06:17
JavaScript
godsplane, 2020-04-23 16:06:17

How to trigger a function on scroll when the page is refreshed?

window.onscroll = function () {
    menuScroll()
  };


  var header = document.getElementById("stick");

  var sticky = header.offsetTop + 500;

  function menuScroll() {
    if (window.pageYOffset > sticky) {
      header.classList.add("sticky");
    } else {
      header.classList.remove("sticky");
    }
  }

If you refresh the page in the middle, then the class is already there right away, is it possible to somehow make the whole process start only after a little scrolling?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
alix_xil, 2020-04-23
@alix_xil

You can add a flag and a counter variable. Calculate page scrolling in the counter and update the flag at some value. Based on the flag, add a class and disable the counter.
I would do that =)

V
Vladimir Ionenko, 2020-04-23
@ionenkovladimir

Right now your function only fires after the scroll event. If you want your function to work after page refresh, then add a function call after page load
document.addEventListener("DOMContentLoaded", menuScroll);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question