Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

media query for vertical scroll

People also ask

Do media queries include scrollbar?

Scrollbar not included in media query width As noted in the older article I linked to, desktop versions of Chrome, Safari, and other WebKit-based browsers do not include the vertical scrollbar in media query widths.

What is only screen in media query?

only screen here is used to prevent older browsers that do not support media queries with media features from applying the specified styles. Follow this answer to receive notifications.


First off, the accepted answer doesn't work.

The correct name is

window.onscroll

and not

window.onScroll

https://developer.mozilla.org/en-US/docs/Web/API/window.onscroll

Second, this is horribly inefficient as the function is called way more than it needs to and can make the page laggy when scrolled. From John Resig:

http://ejohn.org/blog/learning-from-twitter/

Much better to use a timer that runs every 150 ms or so - something like:

var scrolled = false;

window.onscroll = function() {
  scrolled = true;
}

setInterval(function(){
  if (scrolled) {
    scrolled = false;
    // scrollFunction()
  }
}, 150);

I don't believe it's possible with a CSS media query, but I do know that the scroll height can be found in JavaScript using window.pageYOffset. If you wanted to run this value through a function every time the users scrolled up or down on a page, you could do something like

window.onscroll = function() {
    scrollFunctionHere(window.pageYOffset);
};

Or just:

window.onscroll = scrollFunctionHere;

If the function itself checked the value of window.pageYOffset.

For more advice on how to do use window.onscroll efficiently in JavaScript, refer to mynameistechno's answer.

Important note on efficiency: running a function every single time a scroll event is emitted can tear through CPU cycles if anything non-trivial is performed in the callback. Instead, it is good practice to only allow a callback to run so many times per second. This has been termed "debouncing".

Simple debounced scroll event handler code below. Notice how the text toggles between "HELLO" and "WORLD" every 250ms, rather than every single frame:

var outputTo = document.querySelector(".output");
var timeout_debounce;

window.addEventListener("scroll", debounce);

function debounce(event) {
    if(timeout_debounce) {
        return;
    }

    timeout_debounce = setTimeout(clearDebounce, 250);
// Pass the event to the actual callback.
    actualCallback(event);
}

function clearDebounce() {
    timeout_debounce = null;
}

function actualCallback(event) {
// Perform your logic here with no CPU hogging.
  outputTo.innerText = outputTo.innerText === "HELLO"
    ? "WORLD"
    : "HELLO";
}
p {
  padding: 40vh;
  margin: 20vh;
  background: blue;
  color: white;
}
<p class="output">Test!</p>