1

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?

4
  • 1
    You have a typo. The correct method name is attachEvent() (not attack). Commented Sep 7, 2016 at 18:26
  • Do you need to support IE8? Commented Sep 7, 2016 at 18:28
  • A toggle button is one that 'toggles' something on and off. The code you posted looks like code for a search input field. I am quite sure if you search the site you will find how to make a toggle button. Commented Sep 7, 2016 at 20:24
  • Also, what are you trying to 'toggle' on and off? Commented Sep 7, 2016 at 20:27

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.