I have the below code. How can it be triggered automatically when the screen load by defaults or it is refreshed?
function screenSize(){
const mobile = window.matchMedia('screen and (max-width: 573px)');
const tablet = window.matchMedia('screen and (min-width: 572px) and (max-width: 990px)');
const desktop = window.matchMedia('screen and (min-width: 990px)');
mobile.addListener(function(evt){
if(evt.matches) {
alert("Mobile-view")
}
});
tablet.addListener(function(evt){
if(evt.matches) {
alert("Tablet-view")
}
})
desktop.addListener(function(evt){
if(evt.matches) {
alert("desktop-view")
}
});
}
screenSize()
It is only triggered when the viewport is resized. How can I make it fire when the viewport is loaded or refreshed?
Per my comment above, this is a solution to this specific problem. The answer I linked in the comments has some other possible solutions. The core problem is that queries need to be checked for
.matches(bool) on window or document load, not just have listeners added to them.And to use different functions for each breakpoint, you could do it like this: