sina
sina

Reputation: 201

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?

Upvotes: 1

Views: 4484

Answers (2)

MrViK
MrViK

Reputation: 124

You can simply use JQuery to simplify all the proccess. Make all the code as simple as:

function magictoggle(a) {
  if (a == 1) {
    $("#btn1").attr("onclick", "magictoggle(0)");
    $("#searchbox").hide(1000);
    //1000 Are the miliseconds will take the box to hide
  } else {
    $("#btn1").attr("onclick", "magictoggle(1)");
    $("#searchbox").show(1000);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn1" onclick="magictoggle(1)">Search</button>
<input type="text" id="searchbox" placeholder="A search Box">

Upvotes: 0

JonSG
JonSG

Reputation: 13087

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" />

Upvotes: 1

Related Questions