Reputation: 19
I am very new to Javascript and web development as a whole and I'm quite stuck with an If Statement here. The objective of this code is to read if the screen width (or media query) is below 450px, and if so display an alert box - I'm only needing this to work on one page at the moment.
The HTML:
either
<body onload="fullQuote()">
-or- (I'm not sure if the second actually works)
<script>window.onload = fullQuote()</script>
The JavaScript:
function fullQuote() {
var mediaQuery = window.matchMedia("(max-width: 450px)");
if (mediaQuery.matches) {
alert("Test");
}
}
I can't seem to find an answer as to whats wrong with this code anywhere, but I have tried different methods of finding out the screen size like
if (screen.width <= 450) {
if (document.documentElement.clientWidth < 450) {
and also a boolean within the if parentheses:
if (mediaQuery.matches == true) {
among some other ways around this now lost to memory which, of course, shared the same failed results.
Any help to where I am going wrong this matter would be greatly appreciated,
Thanks,
Will
Upvotes: 0
Views: 2103
Reputation: 10916
this will not work because you are invoking the function when setting the window.onload
property. you need to write it like this.
<script>window.onload = fullQuote</script>
this way you are setting window.onload
to equal a function, not the return of the invoked function.
the ideal way to get the screen width is to use window.innerWidth
if(window.innerWidth < 451) //...
if you want to detect changes, you can add a listener on window resize as such.
document.addEventListener('resize', fullQuote);
however i do not recommend using alert while using even listeners as alerts are sync operations, which might cause some problems or jank.
Upvotes: 1