I've been exploring media queries in JavaScript, and it seems like they work well when the window is resized. However, when nested within onscroll
and onclick
functions, things start to get a bit tricky.
If you run the following code and resize the window, everything seems to be fine. But if you set the width of your browser window to 768px, the media query kicks in. Unfortunately, when you start scrolling, it reverts back to the tablet media query, changing the elements' color to tablet mode instead of desktop mode. Even resizing the window doesn't seem to fix this issue when it's nested within a function. How can this be resolved? Make sure to run this code in Full Page mode to resize the window properly.
window.onscroll = function() {stickynavbar();}
var element1 = document.getElementById("element1");
var element2 = document.getElementById("element2");
var myBtn = document.getElementsByTagName("button")[0];
var desktop = window.matchMedia("(min-width: 768px)");
var tablet = window.matchMedia("(min-width: 600px)");
function stickynavbar() {
function element1Query(desktop){
if (desktop.matches){
element1.style.background = "darkred";
}
else{
element1.style.background = "black";
}
}
element1Query(desktop);
desktop.addListener(element1Query);
function element1TQuery(tablet){
if (tablet.matches){
element1.style.background = "darkblue";
}
else{
element1.style.background = "black";
}
}
element1TQuery(tablet);
tablet.addListener(element1TQuery);
function element2Query(desktop){
if (desktop.matches){
element2.style.background = "darkgreen";
}
else{
element2.style.background = "gray";
}
}
element2Query(desktop);
desktop.addListener(element2Query);
function element2TQuery(tablet){
if (tablet.matches){
element2.style.background = "yellow";
}
else{
element2.style.background = "gray";
}
}
element2TQuery(tablet);
tablet.addListener(element2TQuery);
}
.element1{
position: absolute;
top: 0;
left: 0;
width: 50%;
height: 1000px;
background: black;
}
.element2{
position: absolute;
top: 0;
right: 0;
width: 50%;
height: 1000px;
background: gray;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="element1" id="element1"></div>
<div class="element2" id="element2"></div>
</body>
</html>