Javascript: Checking if element is hidden: Media Queries

I am trying to make a simple toggle button, typically I use the code below, of course it won’t work if you’re using media queries to hide the element at a certain breakpoint.

Basically, I want to display:none an element at < 767px, but still open it with the button.

<style>
@media only screen and (max-width:767px){
#dir-map {display:none}
}
</style>

<button onclick="myToggle()">Toggle</button>
<div id="dir-map">
THE Google MAP
</div>


<script>function myToggle() {
  var x = document.getElementById("dir-map");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}</script>

Obviously that won’t work (well unless they click it twice), since #dir-map doesn’t actually have the style inline, it only has it hidden via a media query.

So, basically I need to find a way to check if the element is hidden or not (not just relying on it having the inline style).

You can check on

x.style.display === "" || x.style.display === "none"

or you can just work with “” by settings

x.style.display = "";

in your function

Hi @jeremy58, you can get the actual style with getComputetStyle() like so:

var display = window.getComputedStyle(x).getPropertyValue('display')

if (display === 'none') {
  // ...
}

But then again, why not simply have the button toggle a visible class (say) so you can do the rest with CSS media queries as well (and hide the button altogether for larger MQs)?

x.classList.toggle('visible')
2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.