I'm facing an issue where CSS transitions do not work as expected when triggered by JavaScript.
let isSearchBarOpen = false;
function toggleSearchBar() {
if (isSearchBarOpen) {
searchBar.style.display = "none";
} else {
searchBar.style.display = "flex";
searchBar.classList.add("search-bar-open")
}
isSearchBarOpen = !isSearchBarOpen;
toggleSearchIcon();
}
.search-bar {
display: none;
background-color: #000;
color: #fff;
position: absolute;
top: 0;
left: 0;
right: 0;
padding: 10px 5px;
z-index: 1000;
margin: 0 auto;
transition: top 2s ease-in;
}
.search-bar-open {
top: 90px;
}
<div class="search-icon">
<i class="fas fa-search search-icon-header"></i>
<img src="images/close-icon.svg" alt="close-icon-search" class="close-icon-search">
</div>
<div class="search-bar" id="search-bar">
<div class="search-container">
<form class="search-form">
<input type="text" placeholder="Search...">
<button type="submit"><i class="fas fa-search search-icon-action"></i></button>
</form>
</div>
</div>
Upon clicking the search button, the following sequence of events should occur:
- The function checks the status of
isSearchBarOpen
. - If it is
true
(open), the search bar is hidden using inline style (display:none
). - If it is
false
(closed), the search bar is displayed by applying inline style (display:flex
) and adding the class.search-bar-open
.
Specifying the behavior in the CSS…
When the search bar opens, it applies the
.search-bar-open
class and overrides thedisplay:none
property from the main styling withdisplay:flex
defined in the class.In addition to that, the
.search-bar-open
class is added for further styling changes.The expectation is that the transition specified under
.search-bar
will take place when the.search-bar-open
class is present:
a. Starting at top:0;
…
b. Transitioning smoothly over 2 seconds with ease-in…
c. Ending at top:90px;
.
However, despite these steps, the transition isn't working as intended :-(