One issue arises when using
document.getElementById('table').styles.*
to directly set styling on an element through the DOM. This method gives the styled elements a higher priority than media queries in CSS. As a result, when the media queries are triggered again, they are effectively ignored because of the higher-priority styling applied through the DOM.
Adding or removing classes just through media queries is not possible with the usual .hide .show
approach. Instead, utilizing EventListeners to monitor window resizing and executing the desired functionality becomes the go-to solution.
A helpful resource I came across was this article, which assisted me in crafting a code snippet that fulfills the intended functionality.
JavaScript provides access to window.matchMedia, where all media-related aspects for a document are stored. This feature allows direct manipulation of media-query-like strings within JavaScript instead of being restricted solely to CSS.
For further exploration about media queries, here are some additional resources you may find useful:
To view the full-page example demonstrating window resizing effects, click on the following link.
Using Media Queries
Media Query types
MatchMedia()
'use strict'
if (matchMedia) {
const mq = window.matchMedia("(min-width: 481px)");
mq.addListener(WidthChange);
WidthChange(mq);
}
function WidthChange(mq) {
if (mq.matches) {
view_table();
} else {
close_table();
}
}
function view_table() {
document.getElementById('table').style.visibility = 'visible';
document.getElementById('button2').style.visibility = 'visible';
document.getElementById('button1').style.visibility = 'hidden';
}
function close_table() {
document.getElementById('table').style.visibility = 'hidden';
document.getElementById('button2').style.visibility = 'hidden';
document.getElementById('button1').style.visibility = 'visible';
}
main {
width: 100%;
}
table {
width: 70%;
border: 1px solid black;
margin: auto;
}
.buttons {
margin-top: 5px;
margin-bottom: 5px;
text-align: center;
}
<!DOCTYPE html>
<html>
<head>
<link href="index.css" rel="stylesheet" type="text/css" />
</head>
<body>
<main id="main">
<div class="buttons">
<button id="button1" onclick="view_table()">View table</button>
</div>
<div id="table">
<table>
<tr>
<td>sample</td>
<td>100</td>
<td>10000</td>
</tr>
<tr>
<td>sample</td>
<td>100</td>
<td>10000</td>
</tr>
<tr>
<td>sample</td>
<td>100</td>
<td>10000</td>
</tr>
</table>
</div>
<div class="buttons">
<button id="button2" onclick="close_table()">Hide table</button>
</div>
</main>
</body>
<script src="index.js "></script>
</html>