Having trouble with the jQuery toggle functionality not working as expected

I'm implementing a function where a div should increase in height and opacity when clicked, and then revert back to its original state when clicked again. I used the toggle function for this purpose, but the issue is that the button disappears when the page loads

$(document).ready(function() {
  $('#cm_now').toggle(function() {
    $('.search_bx_ar').css({
      'opacity': '1'
    });
    $('.search_bx_ar').css({
      'height': '40px'
    });
  });
});
.search_bx_ar {
  position: relative;
  margin: 0 0 10px 0;
  width: 100%;
  opacity: 0;
  height: 0px;
  transition: ease-in-out all .5s;
  -webkit-transition: ease-in-out all .5s;
  -moz-transition: ease-in-out all .5s;
}

.compare_sr_btn {
  float: right;
  width: 25%;
  padding-left: 15px;
  margin: 15px 0 10px 0;
}

.compare_sr_btn>#cm_now {
  background-color: #2b7f7f;
  color: #fff;
  border: none;
  height: 40px;
  line-height: 40px;
  width: 100%;
  font-size: 12px;
  text-transform: uppercase;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="compare_sr_btn">
  <input type="button" id="cm_now" value="Compare Now" />
</div>
<div class="search_bx_ar">
  <input class="form-control top_search" id="data_mid" autocomplete="off" onkeyup="autocompl();" type="text" placeholder="Search">
</div>

Answer №1

Toggle isn't quite what you may have expected it to be. The purpose of Toggle is to either hide or display an element. By executing the function immediately upon page load, the button is promptly hidden with a smooth animation.

http://api.jquery.com/toggle/

Take a look at this code snippet to achieve the desired outcome:

var buttonState = 0;

$(document).ready(function() {
    $('#cm_now').click(function() {
        if(buttonState == 0) {
            $('.search_bx_ar').css({'opacity': '1'});
            $('.search_bx_ar').css({'height' : '40px'});
        } else {
            $('.search_bx_ar').css({'opacity': '0.5'});
            $('.search_bx_ar').css({'height' : '20px'});
        }
        buttonState = 1 - buttonState; //a smart way to toggle between 0 and 1
    });
});
.search_bx_ar {
    position: relative;
    margin: 0 0 10px 0;
    width: 100%;
    opacity: 0;
    height: 0px;
transition: ease-in-out all .5s;
-webkit-transition: ease-in-out all .5s;
-moz-transition: ease-in-out all .5s;
}
.compare_sr_btn {
    float: right;
    width: 25%;
    padding-left: 15px;
    margin: 15px 0 10px 0;
}

.compare_sr_btn > #cm_now {
    background-color: #2b7f7f;
    color: #fff;
    border: none;
    height: 40px;
    line-height: 40px;
    width: 100%;
    font-size: 12px;
    text-transform: uppercase;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="compare_sr_btn">
    <button id="cm_now">Compare Now</button>
</div>
<div class="search_bx_ar">
    <input class="form-control top_search" id="data_mid" autocomplete="off" onkeyup="autocompl();" type="text" placeholder="Search">
</div>

Answer №2

$(".click_me").on("click", function() {
  $('.click_me').toggleClass("animate-click");
});
.box_to_animate {
  position: absolute;
  margin: 0 0 20px 0;
  width: 100%;
  opacity: 0;
  height: 0px;
  transition: ease-in-out all .6s;
}

.animation_button {
  float: right;
  width: 25%;
  padding-left: 15px;
  margin-top: 20px;
}

.click_me {
  background-color: #ff5733;
  color: #fff;
  border: none;
  height: 50px;
  line-height: 50px;
  width: 100%;
  font-size: 14px;
}
.animate-click {
    height: 30px;
    opacity: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<div class="animation_button">
          <button class="click_me" type="submit">Animate Now</button>
        </div>
        <div class="box_to_animate">
          <input class="form-control search_input" id="search_data" autocomplete="off" onkeyup="search();" type="text" placeholder="Type to Search">
        </div>

Answer №3

You have neglected to attach a click handler to the toggle button. Instead, you are triggering the toggle function on document ready, which executes as soon as the DOM is loaded.

The toggle() method switches between hiding and showing the selected elements.

When using this method, it checks the visibility of the selected elements. If hidden, show() is executed; if visible, hide() is executed - resulting in a toggle effect.

SNIPPET

$(document).ready(function() {
  $('#cm_now').click(function() {

    $('#cm_now').toggle(function() {
      $('.search_bx_ar').css({
        'opacity': '1'
      });
      $('.search_bx_ar').css({
        'height': '40px'
      });
    });
  });
});
.search_bx_ar {
  position: relative;
  margin: 0 0 10px 0;
  width: 100%;
  opacity: 0;
  height: 0px;
  transition: ease-in-out all .5s;
}

.compare_sr_btn {
  float: right;
  width: 25%;
  padding-left: 15px;
  margin: 15px 0 10px 0;
}

.compare_sr_btn>#cm_now {
  background-color: #2b7f7f;
  color: #fff;
  border: none;
  height: 40px;
  line-height: 40px;
  width: 100%;
  font-size: 12px;
  text-transform: uppercase;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="compare_sr_btn">
  <input type="button" id="cm_now" value="Compare Now" />
</div>
<div class="search_bx_ar">
  <input class="form-control top_search" id="data_mid" autocomplete="off" onkeyup="autocompl();" type="text" placeholder="Search">
</div>

Answer №4

You have the option to toggle your button when it is clicked, otherwise it will toggle and disappear after the document is ready.

$(document).ready(function() {
$("#cm_now").on("click", function() {
  $(this).toggle(function() {
    $('.search_bx_ar').css({
      'opacity': '1'
    });
    $('.search_bx_ar').css({
      'height': '40px'
    });
  });
  });
});
.search_bx_ar {
  position: relative;
  margin: 0 0 10px 0;
  width: 100%;
  opacity: 0;
  height: 0px;
  transition: ease-in-out all .5s;
  -webkit-transition: ease-in-out all .5s;
  -moz-transition: ease-in-out all .5s;
}

.compare_sr_btn {
  float: right;
  width: 25%;
  padding-left: 15px;
  margin: 15px 0 10px 0;
}

.compare_sr_btn>#cm_now {
  background-color: #2b7f7f;
  color: #fff;
  border: none;
  height: 40px;
  line-height: 40px;
  width: 100%;
  font-size: 12px;
  text-transform: uppercase;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="compare_sr_btn">
  <input type="button" id="cm_now" value="Compare Now" />
</div>
<div class="search_bx_ar">
  <input class="form-control top_search" id="data_mid" autocomplete="off" onkeyup="autocompl();" type="text" placeholder="Search">
</div>

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

Trouble with sending SMTP emails from Flask app (Error 500)

Currently, I am in the process of developing a website using Python and Flask where I have successfully implemented a Contact Form Modal. The modal opens up smoothly allowing me to fill it out (many thanks to the supportive community <3), however, upon ...

Using the / (forward slash) in CSS styling statements

Similar Query: Understanding the CSS font shorthand syntax As I was examining the styling on Apple's website, I encountered a CSS rule that left me puzzled: body { font: 12px/18px "Lucida Grande","Lucida Sans Unicode",Helvetica,Arial,Verdana, ...

In React, firebase.firestore() is operational, but firebase.functions() remains undefined

Currently, I am engaged in a React project that heavily relies on Firebase for various features. In order to incorporate HTTPS callable functions into the project, I encountered an issue. The problem lies in the incorrect importation of the 'firebase ...

Unable to display bar chart on PHP webpage showing database number volumes using JavaScript

I'm currently working on generating a bar chart to show the number of bookings per month. I have two separate SQL queries that retrieve the data correctly, as confirmed by testing. However, when I try to run the file in my browser, nothing is displaye ...

Is there a way to deactivate other dropdown options?

To simplify the selection process, I would like to disable the options for "Province", "City", and "Barangay". When the user clicks on the "Region" field, the corresponding "Province" options should be enabled. Then, when a specific province is selected, t ...

How can I add content to the body of a modal in Bootstrap 3?

My application has a button that, when clicked, is supposed to trigger a modal popup containing some data. I want the data in the modal to come from another application via a PHP file accessed through a URL. How can this be achieved? <?php echo '& ...

I am seeking to incorporate several Three.js animations into my HTML document, but I am experiencing issues with them

As a professional graphic designer, I am facing an issue with Three.js https://i.sstatic.net/6ZsWa.jpg I have tried several solutions, but none seem to work effectively. In my attempt, I duplicated the imported model and changed its name. Despite trying ...

Centered title in side menu for Ionic 3

I recently utilized the Ionic CLI to create an Ionic project. The version I am working with is Ionic 3. Currently, I am facing a challenge in centering the title image. Any assistance on this matter would be greatly appreciated. <ion-menu [content]=" ...

Ways to retrieve the file name and additional attributes from a hidden input type

Is it possible to access the file name and other attributes of a hidden file when submitting it using the <input type="hidden"> tag? My current project involves drag and drop file functionality on a server using Node.js. If I am able to dynamically ...

How to send props from a Vue.js component tag in an HTML file

I'm facing an issue with passing props from the HTML to the JavaScript code and then down to a Vue component. Here's a snippet of my index.html file: <div id="js-group-discounts"> <div class="form-group required"> <datepick ...

Using Regular Expressions in JavaScript to verify if an element from an array is contained within a string

Looking for a simple JavaScript code for a Vue application that will split the string into an array and check if any value is present in a different string. Here's what I have: let AffiliationString = " This person goes to Stony Brook" ...

What is the best way to enlarge the image to a specific percentage?

Although I have never programmed in HTML or worked on web projects before, I am currently using a git repository where the project is client-server. This means I need to modify the code to suit my requirements, which includes working with HTML. My problem ...

Vuetify autocomplete with server-side functionality

I am looking to implement infinite pagination on the Vuetify autocomplete feature. My goal is to trigger the loading of a new page of items from the backend when I scroll to the end of the menu. Initially, I attempted using the v-intersect directive as fo ...

Leveraging Vue Data for Storing CSS Properties

I am currently utilizing the Quasar framework in conjunction with Vue for my application development. Below is a snippet of my code: <q-tooltip content-class="bg-amber text-black shadow-4" :offset="[10, 10]"> Save </q-tooltip> <q-tooltip c ...

Error with ajax call in jQuery mobile app

Working on an application using PhoneGap for Android, I encountered an error while running this code block: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> ...

Send myArray via ajax to php

Hey there, I'm currently working on passing an array called myArray to PHP. <script type = "text/javascript" > $(document).ready(function () { var tagApi = $(".tm-input").tagsManager(); var myArray = []; jQuery(".t ...

Implementing Ionic 4 with HTML2Canvas technology

Looking for a way to convert HTML into an image within an Ionic 4 application. I attempted to use html2canvas, however, it was unsuccessful and displayed the following message in the console: Below is the code snippet I used: var element = document.getEl ...

Why is my Vue list not showing the key values from a JavaScript object?

I am struggling to utilize a v-for directive in Vue.js to display the keys of a JavaScript object in a list. Initially, the object is empty but keys and values are populated based on an API call. Here's an example of the data structure (I used JSON.st ...

Is it preferable to include in the global scope or the local scope?

When it comes to requiring a node module, what is the best approach? Should one declare the module in the global scope for accuracy and clarity, or does declaring it in the local scope make more sense? Consider the following examples: Global: let dns = r ...

Unable to execute internal functional tests due to this error: [POST http://localhost:4444/wd/hub/session] unable to connect - ECONNREFUSED

Currently working with node 0.12 and intern 3 in order to execute functional tests, but encountering the following error: SUITE ERROR Error: [POST http://localhost:4444/wd/hub/session] connect ECONNREFUSED at Server.createSession <node_m ...