I'm trying to do something where clicking one div would toggle the display of another div between block and none.
<div id="filtertop" onclick="toggleFilter()">Filter</div>
function toggleFilter() {
let x = document.getElementById("filter").style.display;
if (x == "none") {
x = "flex";
}
else{
x = "none";
}
}
Currently, the code does nothing when I click on the div with id="filtertop"; the display should be changing to none.
You mean that?
function toggleFilter() {
let x = document.getElementById("filter");
if (x.style.display == "none") {
x.style.display = "flex";
} else {
x.style.display = "none";
}
}
<div id="filtertop" onclick="toggleFilter()">Filter</div>
<div id="filter">div with ID</div>
The issue with your code was already explained by @CherryDT within the comments.
Either you have to change your JS to:
function toggleFilter() {
let x = document.getElementById("filter");
if (x == "none") {
x.style.display = "flex";
} else {
x.style.display = "none";
}
}
The smarter and more modern solution would be to use classList.toggle('class-name') as shown in the example below. That applies a CSS class and toggles. Therefore you do not need to use an if / else statement.
function toggleFilter() {
document.querySelector('.filter').classList.toggle('d-none');
}
.filter {
display: flex;
}
.d-none {
display: none;
}
/* for styling purpose only */
.filter {
height: 50vh;
background-color: red;
grow: 1;
margin-top: 20px;
}
#filtertop {
font-size: 2em;
}
<div id="filtertop" onclick="toggleFilter()">Filter</div>
<div class="filter">Filter Element</div>