html - Javascript Screen Width/Media Query If Statement That Returns an Alert Box if True -


i very new javascript , web development whole , i'm quite stuck if statement here. objective of code read if screen width (or media query) below 450px, , if display alert box - i'm needing work on 1 page @ moment.

the html:

either  <body onload="fullquote()">  -or- (i'm not sure if second 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 find answer whats wrong code anywhere, have tried different methods of finding out screen size like

if (screen.width <= 450) { if (document.documentelement.clientwidth < 450) { 

and boolean within if parentheses:

if (mediaquery.matches == true) { 

among other ways around lost memory which, of course, shared same failed results.

any going wrong matter appreciated,

thanks,

will

window.onload

this not work because invoking function when setting window.onload property. need write this.

<script>window.onload = fullquote</script> 

this way setting window.onload equal function, not return of invoked function.

getting screen width

the ideal way screen width use window.innerwidth

if(window.innerwidth < 451) //... 

extra: detect resize

if want detect changes, can add listener on window resize such.

document.addeventlistener('resize', fullquote); 

however not recommend using alert while using listeners alerts sync operations, might cause problems or jank.


Comments