Activate search bar by clicking on it

I am currently attempting a basic jQuery example to expand a search bar on mouse click, but for some reason, my code is not working as expected. I have a simple jQuery function to display the input field when the button with the class "expand" is clicked, however, upon clicking the button, the input field that is originally set to display:none in the CSS does not appear.

Here is my basic jQuery script:

<script type="text/javascript">     
$('.expand').click(function() {
$('#test').show(500);

});

This is my HTML:

 <nav id="menu">
        <ul>

            <li><a href="#">Home</a></li>
            <li><a href="#">Products</a></li>
            <li><a href="#">Contacts</a></li>      
            <li id="sb-search" style="float:right; list-style:none; height:20px;">
            <div id="pesquisar-container">
            <span id="pesquisar" class="form-container cf">
            <form  name="form1" >
                <input id="test" type="search" placeholder="Pesquisar..." required="required" onfocus="if(this.placeholder == 'Search...') {this.placeholder=''}" onblur="if(this.placeholder == ''){this.placeholder ='Search...'}" />
                <button class="expand" type="submit"><i class="fa fa-search"></i></button>
            </form>
            </span> 
           </div>
            </li>
           </ul>
    </nav>   

And this is my CSS styling:

     .form-container input {
    width: 150px;
    height: 25px;
    padding: 5px 5px;
    float: left;    
    font-weight: bold;
    font-size:15px;
    font-family:'bariol_lightlight';
    border: 0;
    background: #f3f3f3; /*#fcfcfc se o fundo for branco, ver as diferenças */
    border-radius: 3px 0 0 3px;  
    margin-top: 9px;  
    color:#000;  
    display:none;
}

    .form-container button {
        overflow: visible;
        position: relative;
        float: right;
        border: 0;
        padding: 0;
        cursor: pointer;
        height: 25px;
        width: 35px;
        text-transform: uppercase;
        background: #363f48;
        border-radius: 0 5px 5px 0;      
        text-shadow: 0 -1px 0 rgba(0, 0 ,0, .3);
        margin-top:9px;
    }  

Answer №1

To ensure your code runs smoothly, consider enclosing it within a DOM ready handler like this: $(function() {...});

$(function() {
    $('.expand').click(function() {
        $('#test').show(500);
    });
});

Answer №2

There are a few possible reasons for this issue. 1. Make sure to add your click listeners within the document ready function. 2. It's recommended to assign an id to the button, such as btnSubmit. 3. You can use the following methods to show or hide elements:

$(selector).hide(speed,callback);
$(selector).show(speed,callback);

Alternatively, you can use the toggle method.

$(document).ready(function() {
    $("#btnSubmit").click(function(){
        $("#test").toggle();
    }); 
});

I hope this solution helps resolve the problem you're experiencing.

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

The hyperlink within the Angular component seems to be unresponsive and is difficult to click on

I attempted to click on the user's profile link, but nothing happens. It seems impossible to interact with it. Here is the code snippet: JavaScript ViewUserProfile(user) { this.router.navigate([user.username]); if (this.currentUser.usernam ...

Managing multiple checkboxes in a Vue component

I have a checkbox component in Vue: <template> <div class="checkbox"> <input class="checkbox-input" name="input" type="checkbox" v-model="checkbox"> </div> </templ ...

Position this menu in the top left corner using HTML and CSS

Is there a way to position the vertical menu completely in the top-left corner without any margin? I've set all margins to 0 but there is still about 2px of space. Any ideas on how to fix this? Thank you in advance! ...

Utilizing jQuery to add elements to a webpage

I need to populate an empty div on my webpage using jQuery. Here's an example: <div class="content"> </div> After the first insertion, I want the markup to look like this: <div class="content"> <div class="inserted first"& ...

Toggle slides smoothly using React

I'm struggling to implement slideToggle functionality in React similar to how I did it with jQuery. The goal is to display a list of recipe headings and hide the content underneath to prevent the page from becoming too long. When a user clicks on a he ...

Cast your vote once for each post within the Angular application

Currently, users are only able to vote up or down once in general. I would like to allow users to vote up or down once per post. <div ng-repeat="post in posts | orderBy:'-upvotes'"> <span class="glyphicon glyphicon-thumbs-up" ...

Have you not heard of the greatness of Selenium before?

I've been trying to automate the process of selecting my shoe size, adding it to the cart, and checking out whenever I visit a sneaker page like FootLocker or FootAction. However, each time I attempt to run the script, I encounter the following error: ...

Adjusting the height of the Bootstrap Modal Container can be a challenging task, especially when there are changes in the

I've been struggling to figure out why my initial modal step is not initializing at the correct height. The angular directive I'm using to set the parent div's height doesn't seem to work on the first modal step. Any ideas why? You can ...

The pop-up menu appears in a location different from where the anchor element is positioned

Having an issue with the menu placement when clicking on an Avatar. The menu is appearing in the wrong position: https://i.sstatic.net/955eJ.png The avatar button "OB" on the right side is where the issue occurs. No console errors present and inspecting ...

Using clearfix on every div element is essential to avoid container collapsing

Would it be beneficial to include clearfix in every div element to avoid container collapse issues? Or is it more practical to apply it only to specific classes, like so? <div class="container"> Additional div elements... </div> .containe ...

Troubles arise with IE8 when using Position: fixed styling

Here is the CSS code I am using: background-color: White; border: 2px solid black; padding: 10px; position: fixed; right: 5px; top: 0; width: 250px; While this code works well in Chrome, Firefox, and Safari, I am facing issues with IE8. The position of t ...

An issue arises when attempting to fetch data using next.js: a TypeError occurs indicating that

I'm currently working on setting up a next.js website integrated with strapi, but I've encountered an issue with my fetch request. Oddly enough, when I test the request using Postman, the data is successfully returned, indicating that the endpoin ...

Ways to relocate the menu within the confines of the "menu border"

Is it possible to move the menu inside the border on this webpage? I am new to web design and was thinking of using position:absolute for the links. Should I also move the submenu along with it? Any suggestions on how to achieve this? Thank you! The goal ...

Using Angular's filter service within a controller

Just starting out so please be kind!! Encountering an issue with Angular 1.3 while using a Stateful Filter within a controller. In brief, when utilizing the $filter('custom')(data) method instead of the {{ data | custom }} method - and the cust ...

Tips for customizing CSS hover effects using HTML and jQuery scripts

Just a heads up before I ask my question - the code I'm about to share is sourced from this video on YouTube, so all credit goes to the creator. JS $(".product-colors span").click(function(){ $(".product-colors span"). ...

Attempting to connect information to state using an input field that is being iterated over in React

Struggling with binding state values to input values using an onChange function handleChange = event => { this.setState({ [event.target.name]: event.target.value }); }; The issue arises when the Input fields are within a map and assi ...

What are the best methods for capturing individual and time-sensitive occurrences within a service?

I am currently working on structuring the events within a service to enable a mechanism for subscribing/unsubscribing listeners when a controller's scope is terminated. Previously, I utilized $rootScope.$on in this manner: if(!$rootScope.$$listeners[& ...

Node.js equivalent of the `Pattern.compile` function

This Java/Android code works perfectly to extract all text between <tag> and </tag> What is the equivalent of this Java code in Node.js/Javascript? private static final Pattern TAG_REGEX = Pattern.compile("<tag>(.+?)</tag>"); pri ...

ng-model fails to synchronize with HTML

When I click on ng-click, the model changes but the HTML remains the same... HTML <p>Reserved:<span>{{seatsInfo}}</span></p> <div ng-click="change()">change</div> JavaScript $scope.seatsInfo = 20; $scope.change = fu ...

The view of the Google map is filled with numerous rounded tiles

Map divided into 3x3 tiles I am looking to customize the appearance of my map and remove all spaces and rounded corners to create a seamless, undivided visual. Is there a way to modify a map tile attribute to achieve this effect? Below is the code snippet ...