Home > Software engineering >  Bootstrap 5: What I need to do to have a search icon in navbar that when I click it, it will show a
Bootstrap 5: What I need to do to have a search icon in navbar that when I click it, it will show a

Time:09-09

This is what I have done so far for the navbar

I need to put a search icon beside log in button. When I click the search icon, a search box will appear under the navbar that look something like in the picture below. My navbar is transparent, position is relative and the header beneath is a video loop with autoplay, position is relative.

Taken from DataCamp website

I have tried free templates codes from other sites but it will give weird results when combined with my existing code and I have tried to change the template codes, still negative results. If possible I want to minimize the usage of js and css so that I can tweak the look easily without hassling too much. Thank you for the help.

CodePudding user response:

You need a flag shouldShowSearchInput. By default, it should be false.

You can use it to change display of Search Input Element to be none or block

When you click SearchIcon changes the value of that flag.

CodePudding user response:

You just need to position the search box under the navbar. Then add a class that will make it visible and add and event listener to the button that toggles that class on and off.

See snippet below

document.querySelector(`#btn-search`).addEventListener(`click`, function() {
  document.querySelector(`#search`).classList.toggle(`show-search`);
});
#search {
  bottom: 0;
  right: 0;
  width: 25%;
  z-index: -1;
  transition: transform 500ms;
  position: absolute;
}

.show-search {
  transform: translate(0, 100%);
}
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.1/css/bootstrap.min.css' integrity='sha512-siwe/oXMhSjGCwLn scraPOWrJxHlUgMBMZXdPe2Tnk3I0x3ESCoLz7WZ5NTH6SZrywMY PB1cjyqJ5jAluCOg==' crossorigin='anonymous' />

<nav >
  <div >
    <ul >
      <li >
        <a  href="#">First Item</a>
      </li>
      <li >
        <a  href="#">Second Item</a>
      </li>
    </ul>
    <div >
      <input type="search" id="search"  placeholder="Search">
      <a  role="button" id="btn-search" href="#">           
  • Related