0

I want to modify this code to make it work only on dekstop devices.

For my case, dekstop is anything above 640px.

Here is the original code:

var prevScrollpos = window.pageYOffset;
window.onscroll = function() {
  var currentScrollPos = window.pageYOffset;
  if (prevScrollpos > currentScrollPos) {
    document.getElementById("shopify-section-header").style.top = "0";
  } else {
    document.getElementById("shopify-section-header").style.top = "-150px";
  }
  prevScrollpos = currentScrollPos;
}
John K
  • 3
  • 1
  • Does this answer your question? [Get the size of the screen, current web page and browser window](https://stackoverflow.com/questions/3437786/get-the-size-of-the-screen-current-web-page-and-browser-window) – zcoop98 Oct 16 '20 at 17:14

1 Answers1

1

var prevScrollpos = window.pageYOffset;
if (window.innerWidth > 640) {
  window.onscroll = function() {
    var currentScrollPos = window.pageYOffset;
    if (prevScrollpos > currentScrollPos) {
      document.getElementById("shopify-section-header").style.top = "0";
    } else {
      document.getElementById("shopify-section-header").style.top = "-150px";
    }
    prevScrollpos = currentScrollPos;
  }
 }

From the MDN Docs (https://developer.mozilla.org/en-US/docs/Web/API/window/innerWidth):

The read-only Window property innerWidth returns the interior width of the window in pixels. This includes the width of the vertical scroll bar, if one is present.

More precisely, innerWidth returns the width of the window's layout viewport. The interior height of the window—the height of the layout viewport—can be obtained from the innerHeight property.

Alternatives:

  • If you can use jQuery: $(window).width()
  • document.documentElement.clientWidth matches the @media queries in css but only when there is no scrollbar
  • window.innerWidth exactly matches css @media queries.

For more about the differences, see How to get the browser viewport dimensions?

Nathan Chu
  • 635
  • 1
  • 3
  • 19