I have this function to toggle elements on click and it works, but I was wondering if there isn't a better solution that could not find
I don't want to use JQuery, only vanilla JS
This is the behavior I need:
- There is one icon that, when clicked, must disappear and show a div
- This div also has a close button that, when clicked, disappears and show the first icon back
Although my solution works, there are 2 problems:
- A CSS inline style (display: none), because that how I could change div's display value back to default (none)
- Div has to be display: none, but I would like it to be a flex container
What is the correct way to do this?
code:
function toggleMe() {
var els = document.getElementsByClassName('togglable');
for (var i = 0; i < els.length; i++) {
if (els[i].style.display == 'none') {
els[i].style.display = '';
} else {
els[i].style.display = 'none';
}
}
}
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<button id="btn" onClick="toggleMe()" class="togglable">
<span id="icon-search" class="fa fa-search fa-5x"></span>
</button>
<!-- voltar pro valor default do display só funciona com css inline -->
<div id="input-container" class="togglable" style="display: flex;">
<input type="text" name="search" onkeyup="search(event);">
<button onClick="toggleMe()">
<span id="icon-close" class="fa fa-times"></span>
</button>
</div>