I’m working on a search bar. First, the user will only be able to see the search icon. When the user clicks on the search icon then that search icon gets replaced with a div that contains a new search bar. I want that when the user click on the search icon the new div with a transition of 1 second in such a way that it looks like the new div was the expanded version of the search icon.
<img src="https://populusww.com.au/wp-content/uploads/2023/01/search.png" id="Search-Collapse" style="cursor: pointer;" onclick="toggle_div_fun();">
<br/><br/>
<script>
function toggle_div_fun() {
debugger;
document.getElementById("Search-Collapse").style.transition = "all 2s";
debugger;
var divelement = document.getElementById("Search-Collapse");
var searchelement =document.getElementById("Search-Expand");
var menusection =document.getElementById("menu-section");
var searchsection =document.getElementById("search-section");
if(divelement.style.display == 'none'){
divelement.style.display = 'block';
searchelement.style.display = 'none';
menusection.style.width = '65%';
searchsection.style.width = '15%';
searchsection.style.marginTop = '30px';
}
else{
divelement.style.display = 'none';
searchelement.style.display = 'block';
menusection.style.width = '65%';
searchsection.style.width = '15%';
searchsection.style.marginTop = '50px';
}
}
</script>
2
Answers
Display did not work with transition, you can use
divelement.style.opacity = 0;
to hide your div with effectand do not forget set opacity for initiate set
divelement.style.opacity = 1;
something like this:
You can do that using CSS opacity in JavaScript simple event listener;
Check this detailed code below if you don’t understand any things let me know and I’ll try to explain it to you 😀
HTML:
CSS:
JS:
and here is a working example on JSFIDDLE