What steps do I need to take in Bootstrap 5 to add a search icon to the navbar that reveals a search box beneath it when clicked?

I've made progress on the navbar design

Now, I'm looking to add a search icon next to the login button. Clicking on the search icon should reveal a search box below the navbar, similar to the image shown below. My transparent navbar has a relative position, while the header underneath is a video loop that plays automatically with a relative position as well.

Image reference from DataCamp website

I attempted using free templates from other websites, but integrating them with my current code resulted in odd outcomes. Even modifying the template codes didn't yield positive results. Ideally, I'd like to minimize the use of JavaScript and CSS to easily adjust the appearance without too much hassle. Thank you for any assistance provided.

Answer №1

To display the search box below the navbar, you first need to position it accordingly and then apply a class to show or hide it based on button clicks.

Here is a quick example:

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 class="navbar navbar-dark navbar-expand bg-dark py-3 position-relative">
  <div class="container">
    <ul class="navbar-nav me-auto">
      <li class="nav-item">
        <a class="nav-link active" href="#">First Item</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Second Item</a>
      </li>
    </ul>
    <div class="d-block">
      <input type="search" id="search" class="form-control position-absolute shadow-sm" placeholder="Search">
      <a class="btn btn-light me-2" role="button" id="btn-search" href="#">🔎</a>
      <a class="btn btn-primary" role="button" href="#">Login</a>
    </div>
  </div>
</nav>

You can also utilize the off-canvas functionality provided by Bootstrap for a similar effect: https://getbootstrap.com/docs/5.2/components/offcanvas/

Check out the off-canvas implementation below:

<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 class="navbar navbar-dark navbar-expand bg-dark py-3 position-relative">
  <div class="container">
    <ul class="navbar-nav me-auto">
      <li class="nav-item">
        <a class="nav-link active" href="#">First Item</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Second Item</a>
      </li>
    </ul>
    <div class="d-block">
      <button class="btn btn-light" type="button" data-bs-toggle="offcanvas" data-bs-target="#offcanvasRight">🔎</button>
      <a class="btn btn-primary" role="button" href="#">Login</a>
    </div>
  </div>
</nav>

<div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasRight">
  <div class="offcanvas-header">
    <h5 class="offcanvas-title" id="offcanvasRightLabel">Offcanvas right</h5>
    <button type="button" class="btn-close" data-bs-dismiss="offcanvas"></button>
  </div>
  <div class="offcanvas-body">
    <input type="search" id="search" class="form-control shadow-sm" placeholder="Search">
  </div>
</div>

<script src='https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.1/js/bootstrap.bundle.min.js' integrity='sha512-1TK4hjCY5+E9H3r5+05bEGbKGyK506WaDPfPe1s/ihwRjr6OtL43zJLzOFQ+/zciONEd+sp7LwrfOCnyukPSsg==' crossorigin='anonymous'></script>

Answer №2

In order to control the visibility of the search input, you will need a boolean variable called shouldShowSearchInput. By default, set this variable to false.

You can utilize this variable to toggle the display property of the Search Input Element between none and block.

Whenever the SearchIcon is clicked, update the value of the shouldShowSearchInput flag accordingly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adjust the scrollbar color when hovering over a particular div

Is there a way to change the color of a div's scrollbar when hovering over the div without assigning an id to it? I've attempted the following methods so far: div:hover { ::-webkit-scrollbar {color: black} } and div:hover + ::-webkit-scroll ...

Encountering a JS error that states: "Uncaught SyntaxError: missing ) after argument list" when running the following code

I keep encountering the error message: "Uncaught SyntaxError: missing ) after argument list" when I try to call the delete function within the createHtmlview function. console.log("Delete Item is being called") } ...

How can I align text to the bottom right and left corners at the same time?

Is there a way to align text so that it appears in both the bottom right and bottom left corners of the page, functioning as a footer? For example: JANUARY (bottom left corner) / 2019 (bottom right corner) If anyone knows how to achieve this using HTML ...

Issue with connecting the 'Enter' key to the button - no success

My current setup involves using jQuery to link the Enter key to an HTML button through this code snippet: $("#console").keyup(function(event){ if(event.keyCode == 13) { $("#submit").click(); } }); HTML: <input autocomplete="off" type= ...

Change the parent title attribute back to its original state

This is in contrast to queries similar to the one referenced here. In my scenario, there is a child element within a parent element (specifically a matSelect within a matCard, although that detail may not be significant) where the parent element has a set ...

The vertical spacing in Font "bottom-padding" appears to be larger than anticipated

Recently, I purchased the font Proxima Nova for my project and I am encountering issues with vertical alignment. Despite setting margins, line-heights, and padding to match those of Arial, the results are not consistent as the Proxima Nova appears misalign ...

What is the best way to link HTML transformations across several classes?

Is it possible to combine multiple transforms in a single element to create a unique end result? It seems that when applying multiple transform properties to an element, only one of them will be recognized. For example, trying to transform a div with bot ...

Trouble updating Kendo DropDown in Internet Explorer

Having an issue with updating a Kendo DropDownList through a javascript function. It works fine in FireFox and Chrome, but not in Internet Explorer. @(Html.Kendo().DropDownList() .Name("myDDL") .HtmlAttributes(new { style = "width: 320px" }) . ...

When a number is added to an array containing strings, the result is a string rather than a number

Currently, I am attempting to change my array key value from a string to a number within my JSON object: form["price"] == "23" console.log(typeof form["price"]) // string form["price"] == Number(parseFloat(this.formObject[field.fieldName])) The issue aris ...

Aligning Bootstrap tags with text in a list can improve the overall appearance

Is there a way to make the tag align perfectly with the text on the left side (see attached image for reference)? I want it to look like this: superlongtagname | text1 shortertagname | text2 tinytagname | text3 Currently, mine looks like this: htt ...

Hovering over the Laravel Breeze dropdown will activate a dropdown feature

Recently, I've been working on a project with Laravel Breeze and have been utilizing some default components. The dropdown component used in the navigation bar caught my attention. By default, it requires a click for the menu to drop down below. Howev ...

Discrepant alignment of form group among the other elements in Bootstrap CSS

Currently, I'm working on an HTML horizontal form that includes buttons and text inputs. I'm using Bootstrap 3 for this project. <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet"/> <fo ...

Creating a unique layout with Bootstrap 5: Custom column heights and dynamic responsive positioning

I've been working on creating a specific layout: My goal is to have the blue column move under the red column when the page size is reduced. No matter what I attempt, the red box keeps trying to match the height of the blue box. Check out my code h ...

Creating a PNG image on a canvas, converting it to a data URL, and then transmitting it using an XMLHttpRequest in NodeJS/Express

I've been experimenting with different methods found on Google, but so far none have worked for me. I'm currently working on implementing the signature-pad, a JavaScript/HTML5 canvas solution for eSignatures. My goal is to save the canvas data as ...

The function will not be triggered when the form is submitted

I've set up this form to send data to the server-side. It's built in HTML/CSS with AngularJS as well. I made sure that the button is placed inside the form, a common mistake that can cause issues. However, despite my efforts, the function "onAddE ...

transfer scope variable to scope function

I notice this pattern frequently view: <input ng-model="vm.model"> <button ng-click="vm.method(vm.model)"></button> controller: function Controller() { var vm = this; this.method = function(parameter) { // perform acti ...

After closing the box, make sure to hold it securely

After clicking the button and closing my box with jQuery (Toggle), I want the state of the box to be remembered after refreshing the page. If the box was closed, it should remain closed upon refresh, and if it was open, it should stay open. I am looking ...

Choose from the options provided to display the table on the screen

One of the challenges I am facing involves a table with two columns and a select option dropdown box. Each row in the table is associated with a color - green indicates good, red indicates bad, and so on. My goal is to have all values displayed when the pa ...

Most effective method to retrieve yesterday's data

Currently, I'm working on a requirement and I need to validate the logic that I've implemented. Can someone help me with this? The task at hand is to calculate the 1 month, 3 month, and 6 month return percentages of a stock price from the curren ...

Having trouble uploading images from my personal computer onto Phaser 3

Currently in the process of coding a game for a school project using Phaser. I am quite new to Phaser and have very little knowledge of JavaScript. Despite searching online for potential solutions, none seem to be effective for me. I have included my cod ...