I am trying to add functionality to a button on a project I’m working on…when the button is pressed I want an element to no longer show on the page. However, I can’t get this process to work. Here is my CSS code for this particular element:
.content-container {
display: flex;
justify-content: center;
align-items: center;
height: 40.06rem;
min-width: 58rem;
background: #ffffff;
box-shadow: 0px 15px 60px rgba(0, 0, 0, 0.25);
border-radius: 36px;
}
Here is my JS code:
//DOM Selectors
const button = document.getElementById("subscribe-button");
const mainPage = document.getElementsByClassName("content-container")[0];
//Event Listeners
button.addEventListener("click", function (e) {
if (mainPage.style.display === "flex") {
mainPage.style.display = "none";
}
});
I added my JS event listener to the button on my page and expected that pressing the button would change the display property from "flex" to "none" and as a result would no longer show the element in question.
However, nothing happens when I press the button.
If I change my JS logic to the following code I can get it to work:
button.addEventListener("click", function (e) {
if (mainPage.style.display === "none") {
mainPage.style.display = "flex";
} else {
mainPage.style.display = "none";
}
});
If I understand correctly, JS sees the default value of the display property as "none" but in this case I have explicitly defined "display: flex" in my CSS so why does the first code block not work but the second work correctly? Additionally, if the second code block is necessary (as it seems to be) is there a more succinct way to write this? It appears that the first block of the if statement isn’t doing anything because it is the "else" block that is doing all the work.
2
Answers
This is not the case, if you define an element in the css stylesheet, the default display property depends on what the element is, for example a
p
isblock
aspan
isinline
, etc.When you are doing the
if
check for themainPage.style.display === "flex"
thatmainPage.style.display
is checking for an inline style that is on the html element. It is not checking the css stylesheet. So, yourif
block fails in the first code block you posted and thus the style is not changed. In the second code block in your example. Theelse
is doing the work because, again, yourif mainPage.style.display === "none"
is failing. To actually check what the display style is on that element (that is set in the css file), you’ll need to do this:You can also help debug things by console logging your
mainPage
element and scroll down to see thedisplay
property is""
an empty string. Which is why your initialif
checks are failing.What I would recommend doing when you click the button is to actually add another class to the div. So for example
.content-container---not-visible
, and then add the styles to the div in cssI’ve personally found it easier to do it that way
You can add a class name using this
element.classList.add("content-container---not-visible");