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