sina sina - 3 months ago 6
Javascript Question

how to make javascript toggle button?

I have this code but it doesn't work:

HTML:

<button id="btn_search">Search</button>
<input id="srh" type="search">


JS:

var btnSearch = document.getElementById("btn_search");
var search = document.getElementById("srh");

if (document.addEventListener) {
btnSeach.addEventListener('click',activeSearch);
} else if (document.attackEvent) {
btnSearch.attackEvent('onclick',activeSearch);
}

function activeSearch (event) {
event.preventDefault();
if (search.style.width == '0') {
search.style.width = '14.8em';
search.style.opacity = '1';
} else if (search.style.width == '14.8em') {
search.style.width = '0';
search.style.opacity = '0';
}


I need a toggle button
What should I do?

Answer

I might think about using a CSS class and toggle() to show/hide you element.

var btnSearch = document.getElementById("btn_search");
btnSearch.addEventListener('click', function(event){
  var search = document.getElementById("srh");
  search.classList.toggle("hidden");
  event.preventDefault();
});
#srh { width: 14.8em; }
#srh.hidden { display: none; }
<button id="btn_search">Search</button>
<input id="srh" type="search" />