Modifying the CSS display property in Javascript following a media query update

Seeking a solution for a table that needs to be visible on desktop but hidden on mobile, with the option of clicking a button to toggle its visibility. Currently, the javascript function close_table() sets display:none which overrides the CSS display:block @min-width 481px, causing issues when resizing the browser from mobile view to desktop. Any advice on ensuring the table remains visible upon increasing the browser size without requiring a page refresh would be greatly appreciated.

Sample code provided below:

HTML :

<button id="Button1" onclick="view_table()">View table</button>
<div id="table">
    <button id="Button2” onclick="close_table()">Hide table</button>
</div>

CSS :

@media (max-width:480px){
    #table {
        display: none;
    }
    #Button1 {
        display: block;
    }
}

@media (min-width:481px){
    #table {
        display: block;
    }
    #Button1 {
        display: none;
    }
}

JS :

function view_table() {
    document.getElementById("table").style.display="block"
}
function close_table() {
    document.getElementById("table").style.display="none"
}

Answer №1

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>

Answer №2

To improve the visibility of elements, consider changing their classes instead.

For example, your HTML code could be structured like this:

<div class="can-be-hidden-on-mobile is-hidden-on-mobile">
    ...
</div>

Next, update your JavaScript accordingly:

document.querySelector(".can-be-hidden-on-mobile").classList.remove("is-hidden-on-mobile");

Lastly, adjust your CSS as follows:

.is-hidden-on-mobile {
    display: none;
}

@media (min-width: 400px) {
    .is-hidden-on-mobile {
        display: block;
    }
}

When the JavaScript executes, the specified class gets removed, and the element is no longer hidden with display: none.

If the user's display width exceeds 400px, the display: block; declaration takes precedence over the previous rule.

Answer №3

Consider incorporating the window resize event:

window.addEventListener("resize", function() {
    if(window.innerWidth > 481) { // checking available space
         displayProducts();
    }else{
        hideProducts();
    }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Positioning a div absolutely while still keeping the integrity of the page layout

I'm in the process of setting up a blog page on my website with a design that includes two columns. The first column, known as .col_1, is fixed in width and is showcased in red. The second column, represented by .col_2, occupies the remaining space an ...

Looking for some guidance on JavaScript and CSS

I have a JavaScript function that animates clouds moving across the screen. I am trying to restrict the area they cover to only occupy the top 300px of the screen. I attempted to add "height:300px; top:0px;" to the DIV style, but it didn't produce th ...

Deactivated the UpdateProgress functionality for the entire webpage

After exploring various options, I came across this solution: Is there a way to disable UpdateProgress for certain async postbacks? However, implementing this solution seems to prevent my controls from loading altogether! In my master page, there is an U ...

How can a controller in AngularJS detect when the back button of the browser is pressed

I've created a browser trivia game where authenticated players can select a game type, triggering a socket.io event in my Node.js server. The view then transitions to a "Searching for game" screen with a loading icon as the server waits for enough pla ...

A guide on how to navigate the parent window from a child window

When using my application, I have a function that opens a new window like this: window.open("www.example.com"); Within the new window, there is a button. Upon clicking this button, the new window should close and then redirect the parent window to a diff ...

What is the reasoning behind placing CDN links at the bottom of the index file?

What is the reason for placing CDN links for AngularJS file at the end of the index page? I initially placed it at the top of the file and it worked fine. Is there a significant difference between these two placements? ...

The checkbox label should be centered directly beneath the checkbox

I'm feeling a bit lost. I came across this code snippet on jsfiddle: https://jsfiddle.net/rx90f38u/1/ There seems to be some styling included, but I can't figure out why the "remember" me text is showing below the checkbox. The checkbox and it ...

The installation of npm modules is failing with the error message: "'react-scripts' is not recognized as a valid command, internally or externally."

As I revisited my old project on GitHub, things were running smoothly a few months prior. However, upon attempting to npm install, I noticed the presence of the node modules folder and encountered some npm errors. https://i.stack.imgur.com/awvjt.png Sub ...

The date-picker element cannot be selected by html2canvas

I'm encountering an issue with Html2canvas while trying to capture a screenshot of my page. Specifically, the date shown in the date-picker on the page is not appearing in the screenshot. Do you have any insights into why this might be happening and h ...

Can one validate a single route parameter on its own?

Imagine a scenario where the route is structured as follows: companies/{companyId}/departments/{departmentId}/employees How can we validate each of the resource ids (companyId, departmentId) separately? I attempted the following approach, but unfortunate ...

Activate the q-file toggle for the Quasar framework when a different button is selected

How can I make the file selector q-file toggle in Quasar framework when a specific button is clicked? My current attempt: When this button is clicked, it should toggle the q-file: <button @click="toggleFileSelector">Toggle File Selector&l ...

The jQuery .Text() method efficiently replaces the contents of an element with fresh

I am experiencing an issue where the .text() function in jQuery replaces both the text and HTML within an element. I'm looking for a solution that allows me to only modify the actual text and leave the HTML intact. Any ideas on how I can achieve this? ...

Encountering a problem with Chrome Extension localization upon installation - receiving an error message claiming default locale was not specified, despite having

Error Message: "The package has been deemed invalid due to the following reason: 'Localization was utilized, however default_locale was not specified in the manifest.' Issue: I have developed a customized extension and defined a default locale, ...

React.js onClick does not display the dropdown

Hello, I have a question regarding my navbar icon functionality. When I click on the icon, it is supposed to open a dropdown menu. However, although the div name changes when clicked, the CSS properties remain the same as the initial class. I am unsure w ...

Creating a Burger Navigation Menu with CSS and HTML using Image Overlapping

I'm encountering an issue with the new website I created for my local Church. I followed a tutorial on building a burger menu using just HTML and CSS, which you can view here. The problem arises when I attempt to place an image below the navigation m ...

Elements appearing distorted in Firefox and Internet Explorer

I'm completely new to the world of web development and I am attempting to construct a website for my company all by myself. However, I am encountering an issue with a "red info box" on one of my pages. While it displays perfectly on Chrome, it appear ...

How can I determine in JavaScript if the Backspace key is being long pressed on iOS or Android devices?

In the process of developing a web application using Vue.js, I encountered an issue with detecting long presses of the Backspace key on desktop keyboards (Windows PCs specifically). On desktop, the event triggers multiple times as long as the Backspace key ...

How can transitions be activated in Bootstrap 4 carousel?

Having an issue with my Bootstrap 4 carousel where I need to move 4 slides at a time. I have tried using the code below: $(this).carousel(4); However, the problem is that the carousel only jumps to that index without showing any transitions. Using $(this) ...

Why won't my JavaScript addEventListener activate on form submission?

I have a basic question as a beginner in JavaScript. I am facing some challenges with my first task involving JavaScript. I decided to learn JS by creating a TODO List, but I am stuck right at the beginning. The event listener that should respond when the ...

Error found in Twitter Bootstrap popover plugin: `this.isHTML` function is missing

I took the example directly from their website: http://jsfiddle.net/D2RLR/631/ ... and encountered the following error: this.isHTML is not a function [Break On This Error] $tip.find('.popover-title')[this.isHTML(title) ? 'html&apos ...