Is it possible to retrieve the current CSS value set by a media query using JavaScript?

Currently working on a website project that involves accessing and manipulating the display property of a menu. The goal is to toggle the menu open or closed based on its current state.

In my setup, the initial state of the menu is defined as closed using a responsive media query (where it's forced to stay open if the width exceeds a certain value with !important in the media query). The rest of the functionality is controlled through JavaScript:

var attach_menu_control = function() {
  var $sidebar = document.querySelector('.sidebar')
  var $sidebar_content = document.querySelector('.sidebar .content')
  var $menu_opener = document.querySelector('.sidebar .menu-closed')

  var hide_menu = function() {
    console.log('Hide menu is run.')
    $sidebar_content.style.display = 'none'
    $menu_opener.style.display = 'block'
    $sidebar.style.width = '40px'
  }

  var show_menu = function() {
    console.log('Show menu is run.')
    $sidebar_content.style.display = 'block'
    $menu_opener.style.display = 'none'
    $sidebar.style.width = '270px'
  }

  var click_handler = function(e){
    console.log('Click handler is run.')
    debugger
    var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
    if ($sidebar_content.style.display == 'none') { // Here it is `""` instead of `none`
      show_menu()
    } else if (width <= 724) {
      hide_menu()
    }
  }

  var $main = document.querySelector('main')

  $main.addEventListener('click', hide_menu)
  $sidebar.addEventListener('click', click_handler)

  var event = new Event('click');
  $sidebar.dispatchEvent(event)
}

Encountering an issue where upon the first execution, the $sidebar_content.style.display returns an empty string "" despite being set to display: none in the media query:

@media only screen and (max-width: 724px) {


    /* Force sideback to be in closed mode when new page is opened */
    .sidebar {
        width: 40px;
    }

    .sidebar .content {
        display: none;
    }
}

Is there a way to access values set by media queries within JavaScript? Not interested in retrieving the rules themselves, just need the current set value.

You can view the site here: www.saulesinterjerai.lt

Answer №1

Based on my interpretation of the initial query, it seems that there is an interest in accessing the current CSS values after considering @media settings.

I suggest using the following code to retrieve the current rendered status of the element:

window.getComputedStyle($sidebar_content)

It's important to note that in modern web browsers, there might be a slight delay between applying a style or class and the page reflow. Therefore, it may be necessary to implement a timeout function and check the computed value after a brief pause. Your mileage may vary.

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

I noticed that my CSS style sheet is only working on three of my pages. What should I do to make sure it affects the fourth page as well?

I am currently facing an issue with my website where I have linked one .css stylesheet to 3 different pages. This is just a temporary template until I finalize the individual look of each page. After performing some div positioning on the site, most pages ...

The MuiPrivateTabScrollButton alters the dimensions and flexibility properties using CSS

I have been facing a challenge with overwriting the css of MuiPrivateTabScrollButton. Since this class is generated from material ui, I am unable to successfully overwrite it. Despite debugging and trying various fixes such as adding border colors, I still ...

Passing a list variable to JavaScript from Django: A step-by-step guide

Currently, I am facing an issue while attempting to generate a chart using Chartjs and Django. The problem arises when transferring data from views.py to the JavaScript code. Here is a snippet of my code in views.py: def home(request): labels = [&quo ...

AngularJS - Move the <li> element to the top when its corresponding checkbox is selected

This particular question pertains to a topic that was previously discussed in another thread The scenario involves using a ng-repeat as shown below: <li ng-repeat="opt in namesCtrl.uniqueCars"> <input type="checkbox" ng-model="namesCtrl.filt ...

What are the steps to display the entire image instead of a cropped version?

Currently in the process of constructing a website using HTML/CSS/Bootstrap/Js. I have encountered an issue while attempting to overlay a jumbotron on a container with a background image utilizing z-index. Unfortunately, the background image I am using k ...

Is it possible to display a div when hovering over it and have it remain visible until

How can I make the div ".socialIconsShow" fade in when hovering over ".socialIcons", and then fade out when hovering over ".socialIconsShow"? Is there a way to keep the icons visible even after leaving ".socialIcons"? <div class="socialNetworks"> ...

Adding static JSON array data to the results received from an API call

Within my code snippet below, I am able to retrieve a JSON Response: respArray = [] respArray = respBody.classifiers respBody = respArray if (respBody.length > 0) { respBody = applyPagination(respBody, reqParams.filter, option ...

Is it feasible to run a function immediately following a reload?

Recently, I came across a code snippet that intrigued me: setTimeout(function() { window.location.reload(true); if ($scope.attribute.parentAttribute.id) { angular.element(document.getElementById($scope.attribute.parentAttribute.id)).click(); ...

Using HTML to design interactive buttons that can send API requests and display their current status

Seeking assistance with creating buttons to control a remote light's ON and OFF states while reflecting their status as well. The specific http API calls for the light are necessary to toggle its state. Turn On = http://192.168.102.22:3480/data_requ ...

Error: Attempting to access 'push' property on an undefined object

Encountered an Error After implementing the useNavigate function, I successfully resolved the issue. let params = useParams(); let navigate = useNavigate(); const dispatch = useDispatch(); const productId = params.id; const [qty, setQty] = useStat ...

Column count pseudo class is malfunctioning on Safari browser

Why is the pseudo class with column count not working in the Safari browser? I have captured two screenshots to illustrate this issue. 1. Firefox browser screenshot https://i.sstatic.net/27uoI.png 2. Safari browser screenshot https://i.sstatic.net/vRN ...

Rendering HTML or links sourced from encoded JSON data with JavaScript

After making an ajax call, I receive the following data: {"dataList":[{"date":"August 27, 2013","text":"<a href=\"http:\/\/www.example.com\/test.aif\" title=\"Click here to listen\" target=\"\">Click her ...

Is it possible to enter NaN in Vue3?

Is there a way to handle NaN values and keep a field blank instead when calculating margins with a formula? https://i.stack.imgur.com/JvIRQ.png Template <form> <div class="row"> <div class="mb-3 col-sm ...

I am having an issue with the npm install command. Each time I try running it, I keep receiving an

After posting the output, I find myself unable to comprehend anything. Can someone please guide me on what steps to take next? npm has issued a warning about an old lockfile and advises that supplemental metadata needs to be fetched from the registry due t ...

Troubleshooting the Issue with Jquery Menu and Mouse Pointer

Recently, I've been attempting to modify the cursor behavior on a navigation menu that I stumbled upon at HTML Drive's JQuery Menu. I experimented with CSS and jQuery. In my JQuery attempt, I utilized... $("body").hover(function() { $(this).cs ...

Can you point me in the direction of some resources for developing a custom plugin with stylelint?

After visiting the stylelint website and github, I downloaded it locally using npm. The stylelint website suggests using the following format to create my own plugin: var myPluginRule = stylelint.createPlugin(ruleName, function(primaryOption, secondaryOpt ...

A different approach for dynamically displaying React components sourced from an API

As I develop a website using Next.js/React that pulls in content from Strapi CMS, my goal is to create a dynamic page template for news articles. The aim is to empower content editors by giving them the flexibility to choose the type of content they wish t ...

Guide to selecting an element with a combination of text and a random number using Selenium with JavaScript

<a id="Message4217" class="btn-sm btn-danger Message" data-id="4217"><span class="icon-adjustment icon-trash"></span> Delete</a> The objective is to remove a message base ...

What could be causing the 404 error I'm receiving for this specific URL?

Can someone explain why I keep encountering a 404 error when I type \book into the URL bar? Below is the code I am currently using: var express = require('express'), app = express(), chalk = require('chalk'), debug = ...

Can one customize the background color of a segment in a radar chart using Chart.js?

Could I customize the color of the sectors in my radar chart to resemble this specific image? https://i.stack.imgur.com/U8RAb.png Is it feasible to achieve this using Chart.js? Alternatively, are there other chart libraries that have this capability? It ...