Js scroll functon help

Can anyone explain this script to me as beginner and detailed as possible:

var prevScrollpos = window.pageYOffset;
window.onscroll = function() {
var currentScrollPos = window.pageYOffset;
if (prevScrollpos < 40)
{ document.getElementById(“MenuSvommehal”).style.top = “38px”;
}
else {
document.getElementById(“MenuSvommehal”).style.top = “0”;
}
prevScrollpos = currentScrollPos;
}

Why don’t you tell us which lines you don’t understand so we don’t waste your time and our time explaining something you already understand?

1 Like

It will just be nice with an explanation of it all?

  1. Get the current pageYOffset value (prevScrollpos).

pageYOffset

returns the number of pixels the document is currently scrolled along the vertical axis (that is, up or down) with a value of 0.0, indicating that the top edge of the Document is currently aligned with the top edge of the window’s content area.

  1. On page scroll (onscroll) call the anonymous function.

  2. Grab the new value of pageYOffset (currentScrollPos) after the page has scrolled.

  3. If the first pageYOffset value (prevScrollpos) is less then 40 set the element with an id of MenuSvommehal top property to 38px, else set it to 0.

  4. Update the first pageYOffset value (prevScrollpos) to be the same as the second value (currentScrollPos) so when the page is scrolled again the compare starts from this value.

It is likely used to make a sticky nav or menu.

Here is a quick, not so great example.
https://codepen.io/anon/pen/OeNVea

I think this code is to make a fixed menu on scroll, I commented the code. Good Luck !

var prevScrollpos = window.pageYOffset;`
//This is a function which is started when you do a scroll into page
window.onscroll = function() {
// get current position onscroll and stores the Y axis in the currentScrollPos var
var currentScrollPos = window.pageYOffset;
// if prevScrollPos is < 40 then set the top to 38px
if (prevScrollpos < 40)
{ document.getElementById(“MenuSvommehal”).style.top = “38px”;
}
// If prevScrollPos is greather than 40 then change the style of the element with Id MenuSvommehal
else {
document.getElementById(“MenuSvommehal”).style.top = “0”;
}
// get the new scroll position and store it in the prevScrollpos to update the value
prevScrollpos = currentScrollPos;
}