1

For my project I want a parallax scrolling effect only if the screen size is equal or wider than 800px. To do this I wrote following code:

<script>
    if (window.screen.width >= 800) {
        function parallax() {
            var parallax = document.getElementById("box01");
            parallax.style.top = -(window.pageYOffset / 4) + "px";

        }
    }

    window.addEventListener("scroll", parallax, false);

</script>

The parallax scrolling works fine but the "window.screen.width" command is ignored by the browser. Means: The parallax scrolling is also enabled for screen smaller than 800px.

Any help is appreciated!

3 Answers 3

2

What you're looking for is window.matchMedia.

function executeIfMinWidth800 (e) {
  if (window.matchMedia('(min-width: 800px)').matches) {
    // do stuff
  }
}

// call initially
executeIfMinWidth800();

// add handler for resize
window.addEventListener('resize', executeIfMinWidth800);
Sign up to request clarification or add additional context in comments.

2 Comments

Works now! Thanks heaps!
This is a thing? I love how simple this is.
0

window.screen gets you the size of the monitor.

What you want is the size of the viewport, accessible via:

// width
window.innerWidth
// height
window.innerHeight

Comments

0

You should try this

if (window.matchMedia('(min-width: 800px)').matches) {
  function parallax() {
        var parallax = document.getElementById("box01");
        parallax.style.top = -(window.pageYOffset / 4) + "px";

    }
} else {};
window.addEventListener("scroll", parallax, false);

1 Comment

Thanks for the help! This works fine but only on reload.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.