Reputation: 15
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!
Upvotes: 1
Views: 400
Reputation: 938
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);
Upvotes: 0
Reputation: 21926
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);
Upvotes: 2
Reputation: 22949
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
Upvotes: 0