'Javascript classList.add to element with 0px height
Not sure if I'm missing something obvious here, but I'm trying to add a class to an element that has 0px
height to begin with.
const teamMemberBioShow = function() {
const bio = document.querySelector(".bio");
if (bio.classList.contains("hidden")) {
bio.classList.remove("hidden");
bio.classList.add("show");
} else {
bio.classList.remove("show");
bio.classList.add("hidden");
}
}
const teamMemberBioMore = document.querySelector(".bio-more");
teamMemberBioMore.addEventListener('click', teamMemberBioShow);
.bio.hidden {
opacity: 0;
height: 0;
}
.bio.show {
opacity: 1;
height: auto;
}
<div class="bio hidden">
Bio goes here
</div>
<div class="bio-more">Read Bio</div>
On click, the class .show
is added and the .hidden
class is removed. But it doesn't work if the .hidden
class has 0px
assigned to it.
Solution 1:[1]
The problem is that if you put height 0 but do not set the overflow: hidden
the text content of that div will overflow and cover the clickable text, so the click event won't be dispatched:
const teamMemberBioShow = function() {
const bio = document.querySelector(".bio");
if (bio.classList.contains("hidden")) {
bio.classList.remove("hidden");
bio.classList.add("show");
} else {
bio.classList.remove("show");
bio.classList.add("hidden");
}
}
const teamMemberBioMore = document.querySelector(".bio-more");
teamMemberBioMore.addEventListener('click', teamMemberBioShow);
.bio.hidden {
opacity: 0;
height: 0;
overflow: hidden;
}
.bio.show {
opacity: 1;
height: auto;
}
<div class="bio hidden">
Bio goes here
</div>
<div class="bio-more">Read Bio</div>
Solution 2:[2]
This is because even if your element .bio.hidden has an opacity of 0, it messes up with the click event, and it overflows over the other div.
Try putting display: none
if you want to hide an element
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Cesare Polonara |
Solution 2 | Ilphrin |