Reputation: 221
so I want to check if a CSS variable is 0px, and then to console.log
a message saying "Make Big". This is the if statement I have tried using:
const root = document.documentElement
const toggleNavButton = document.querySelector('.nav-dropdown');
toggleNavButton.addEventListener('click', () => {
console.log(getComputedStyle(root).getPropertyValue('--mobile-navbar-height'))
if (getComputedStyle(root).getPropertyValue('--mobile-navbar-height') === '0px') {
console.log('Make big');
}
});
And this is the CSS variable:
:root {
--mobile-navbar-height: 0px;
}
This is the HTML:
<html lang="en">
<head>
<title>Frontend - Sign Up</title>
<link rel="stylesheet" href="../styles/styles.css">
<script defer src="../scripts/UI_Manager.js"></script>
</head>
<body>
<header>
<nav class="top-nav">
<ul class="nav-link-container">
<li class="nav-item nav-all">TITLE</li>
<li class="nav-item nav-full">ITEM 1</li>
<li class="nav-item nav-full">ITEM 2</li>
<li class="nav-item nav-full">ITEM 3</li>
<li class="nav-item nav-dropdown">
<span>🍔</span>
</li>
</ul>
</nav>
</header>
</body>
</html>
This is the ouput in the console:
Any help would be appreciated, thanks.
EDIT: Thanks for all your help.
Upvotes: 0
Views: 710
Reputation: 9984
Your code is returning 0px
(There is a space before the 0)
Example comparing with a space:
const root = document.documentElement
const toggleNavButton = document.querySelector('.nav-dropdown');
toggleNavButton.addEventListener('click', () => {
var style = getComputedStyle(root).getPropertyValue('--mobile-navbar-height')
console.log(style)
if (style === ' 0px') {
console.log('Make big');
}
});
:root {
--mobile-navbar-height: 0px;
}
<button type='button' class='nav-dropdown'>Dropdown example</button>
You can either expect that in the comparison, or .trim()
the string to remove extra space at the start/end before doing the comparison (Trimming is likely more reliable)
Trimming example:
const root = document.documentElement
const toggleNavButton = document.querySelector('.nav-dropdown');
toggleNavButton.addEventListener('click', () => {
var style = getComputedStyle(root).getPropertyValue('--mobile-navbar-height').trim()
console.log(style)
if (style === '0px') {
console.log('Make big');
}
});
:root {
--mobile-navbar-height: 0px;
}
<button type='button' class='nav-dropdown'>Dropdown example</button>
Upvotes: 1
Reputation: 3124
Trim the value you are getting extra space
change line
getComputedStyle(root).getPropertyValue('--mobile-navbar-height') === '0px'
to
getComputedStyle(root).getPropertyValue('--mobile-navbar-height').trim() === '0px'
Upvotes: 0