Show and conceal a search container with jQuery

I am in the process of designing a website that features a search icon within the navbar. When the user clicks on the search icon, it should disappear by applying the "hide" class to itself. Additionally, the hide class should be removed from a separate search bar div. Unfortunately, my jQuery implementation for this functionality is not functioning correctly. How can I address this issue?

Below is a snippet of the relevant code-

Bootstrap CSS-

<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">

Body-

<li class="hvr-bounce-to-bottom" id="navbar-search">
<a href="">
<span class="glyphicon glyphicon-search" aria-hidden="true"></span>
</a>
</li>
<div class="input-group width-174px margin-top-8px hide" id="navbar-searchbar">
<input type="text" class="form-control width-100px" placeholder="Search">
<span class="input-group-btn">
<button class="btn btn-default" type="button"><span class="glyphicon glyphicon-search" id="navbar-search" aria-hidden="true"></span></button>
</span>
</div>

JS-

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<script src="custom.js"></script>
$('#navbar-search').on('click', function(){
$(this).addClass('hide');
$('#navbar-searchbar').removeClass('hide');
});

Answer №1

Your issue arises from the placement of your icon within an anchor element, which triggers the default click behavior of the anchor upon clicking the icon.

To resolve this, you can prevent this default behavior by using the event.preventDefault() method.

$('#navbar-search').on('click', function(e) {
  e.preventDefault();
  $(this).addClass('hide');
  $('#navbar-searchbar').removeClass('hide');
});
<script type="text/javascript" src="//code.jquery.com/jquery-1.10.1.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap-theme.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/js/bootstrap.js"></script>

<ul>
  <li class="hvr-bounce-to-bottom" id="navbar-search">
    <a href="">
      <span class="glyphicon glyphicon-search" aria-hidden="true"></span>
    </a>
  </li>

</ul>
<div class="input-group width-174px margin-top-8px hide" id="navbar-searchbar">
  <input type="text" class="form-control width-100px" placeholder="Search">
  <span class="input-group-btn">
<button class="btn btn-default" type="button"><span class="glyphicon glyphicon-search" id="navbar-search" aria-hidden="true"></span></button>
  </span>
</div>

Answer №2

No need to create a separate class for this task. You can simply do the following:

$('#navbar-search').hide()
// AND
$('#navbar-search').show()

If you prefer toggling, use:

$('#navbar-search').toggle()

Additionally, make sure you are consistent with the IDs you're using. If you add the class "hide" to #navbar-search, then try to remove it from #navbar-searchbar, it won't work unless both elements have the same ID.

Based on my understanding, your revised code should look like this:

$('#navbar-search').click(function(){
      $('#navbar-searchbar').toggle()
})

Answer №3

Try applying the hidden class or visible class as shown below:

This div will only be visible on extra small screens (xs).

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

Experimenting with a function that initiates the downloading of a file using jest

I'm currently trying to test a function using the JEST library (I also have enzyme in my project), but I've hit a wall. To summarize, this function is used to export data that has been prepared beforehand. I manipulate some data and then pass it ...

Arranging DataTable by the newest date

I need to change the default sorting of a table from old date to recent date (1st column). Here is the code I have been trying: <script> $(document).ready( function () { $('#table_id').DataTable({ dom: 'B<"cle ...

Programmatically setting properties for elements

I have a question about how to programmatically add a prop to a component in my React project. Here is the scenario: In the render() method, I have the following code snippet: <TextField name="password" va ...

Buttons containing two lines of text appear bigger compared to those with only one line of text, but it is essential for all buttons to be consistent in size with the single line buttons

I am facing an issue with the buttons on my website, as they seem to resize based on the amount of text present. When there are 2 lines of text, the buttons appear larger compared to those with just one line. How can I rectify this situation? Although thi ...

What is the best way to get jsDoc "import" to function properly in vscode?

Is it possible to import a node module using @import in Visual Studio Code? I'm trying it but it doesn't seem to be recognized. Am I missing something? https://i.stack.imgur.com/zq1rz.png ...

Function with jQuery click event and namespace

Why is it illegal in jQuery? $('#someElm').on('click', customNamespace.namespaceFunction); jQuery throws an error: Uncaught TypeError: undefined is not a function Note: The functions are not important... let's use them for illus ...

What is the significance of using $timeout in order to activate a watch function?

There is an interesting phenomenon happening with my directive. It watches the height of an element that is being updated by a controller using a factory method to retrieve data. Strangely, unless I include a $timeout in that factory function, my watch doe ...

What is the best way to retrieve values from a nested mongodb object?

I am currently working with a Company mongodb structure that looks like this: { "companyName" : "SomeCompany", "Products" : [ { "productId" : "e3rQACssGkfp9zsue", "productCode" : "271102502", "memberPrice" : " ...

Vue.js's @click feature can be enhanced with ternary operations

I've been attempting to achieve the following in Vue.js, but I keep encountering an error that says [plugin:vite:vue] Unexpected token (1:27): @click="selectedFiles.push(file.id); selectedFiles.length < 1 ? isCollapse=false: isCollapse=true&q ...

In PHP, the hidden input type doesn't always provide true concealment within a form if the value being passed

I am attempting to populate a hidden input field with the value of an XML string generated from an array. However, when I set the hidden field value using the XML string, it is being displayed in the HTML output. Surprisingly, if I use plain text as the va ...

Strategies for sorting data in d3js/dimplejs visualizations

I am looking to enhance the interactivity and responsiveness of a d3js/dimplejs chart by implementing filtering based on clicks in the legends for different series. The code I tried below did not hide the series as expected, although it worked well with a ...

Default Filter for Lookup Dialog in Dynamics CRM 2011

I am attempting to customize a lookup dialog to default to a specific entity type. While working on the Connection form, I am checking the entity type of record1id and attempting to use that information to set the defaulttype attribute on record2id. My c ...

Register with Django directly on the start page without being redirected to the login page

My experience with Django is quite limited, although I do have a grasp on the basics of Python. Currently, I am working on developing a web application that will be integrated with a Fortran code for the summer. The Fortran code generates data, and my goal ...

Is there a way to store div content in a PHP Session?

Just starting to learn php & ajax, so be patient with me. I have a clickable map. When the user clicks on a point, the value is displayed in a div. Once they select a point, they should be able to proceed to the next step. Now I want to save the content ...

Condense everything when displaying one at a time (various divs)

I found the solution at https://getbootstrap.com/docs/4.2/components/collapse/ My query is related to collapsing multiple elements and showing only one when divided into different divs. While it works within the same div, dividing content into separate di ...

Search for data in MongoDB based on the results obtained from the initial query

I am facing an issue with a mongoose query: let rE = await cR.find({myid: "xxxxxx"}); This query returns multiple results, and then I need to query another model based on the rE.class_id value. So I try to do this: let cla = await Cl.find({_id: ...

Highlight a pair of words in a phrase using jquery technology

Only one word in my code is highlighted $(document).ready(function() { let firstword = 'web'; let secondword = 'js'; $(".field.ConditionsAccept>.caption:contains('" + secondword + "'):contains('" + firstword ...

Jquery attribute not functioning correctly when setting the 'required' property for checkboxes

One of the challenges I am facing is trying to toggle a text box on a checkbox's click event. While I have achieved success in this aspect, my issue lies in changing the checkbox's required attribute as well. Below is the code that successfully ...

Issue with the JSON response in MVC 4

I have been struggling to bind JSON values to specific text boxes. It works with dynamically created textboxes but not with static ones that are already present. I've been stuck on this issue for 2 days and despite searching the internet, I couldn&apo ...

Converting JSON DateTime objects to local time in JQuery without considering timezones

I am struggling with parsing a JSON DateTime object using moment.js. Despite trying various methods recommended on Stackoverflow, nothing seems to work in my case. In my application, I save DateTime values in UTC format and when displaying them, I need to ...