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

Error encountered: Vue.js encountered an unexpected token, which is 'export'

Having an issue with Google location autocomplete, specifically this error: SyntaxError Unexpected token 'export' Here is the link to the functional code: https://codesandbox.io/s/nifty-bardeen-5eock ...

What steps should I take to troubleshoot and resolve the connection issue that arises while trying to execute npm install

Following the guidelines from: https://www.electronjs.org/docs/tutorial/first-app I executed commands like mkdir, cd, and npm init. They all ran successfully, generating a file named package.json. Subsequently, I entered npm install --save-dev electron w ...

When it comes to deploying middleware, accessing cookies becomes more challenging. However, in a local setup, Next.js allows middleware to

I have set up a NextJS frontend application with a backend powered by NodeJS and ExpressJS. Authentication and authorization are handled using JWT token-based system, where the backend server sets the token and the frontend server validates it to grant acc ...

Iterating over a table and selecting a specific button on the rows that meet a specific condition

I'm having a bit of trouble and would really appreciate your help. I'm attempting to write a script that will scan through this table and delete any row that contains the word "active". The script needs to check every row in the table. The code ...

What is the best way to stack several items vertically beside an image?

As a beginner in the world of web development, I recently embarked on my first project. However, I am facing an issue where I cannot align multiple elements under each other next to an image. One element floats at the top beside the image, while the other ...

HeaderView in Angular Framework

When exploring the best practices for organizing an AngularJS structure, I came across the recommendation to implement partial views as directives. Following this advice, I created a directive for my app header. In my specific header design, I included a ...

What is the best way to format dates in jQuery AJAX requests?

Utilizing jquery to interact with a REST API in (ASP.net Web API). I've constructed a basic object and then utilized jquery to 'PUT' it on the server: var myObject = { name: 'just a name', createDate: new Date() } $.ajax({ ...

Setting orientations for portrait and landscape views using Material UI breakpoints

Looking to implement portrait and landscape views for tablets using the styles object in Material UI. const tabletStyles = theme => ({ root: { padding: theme.spacing.unit, [theme.breakpoints.up('md')]: { backgroundColor: theme ...

Encase all jQuery functionalities within a custom class

I am looking to create a JavaScript class that encapsulates jQuery's DOM functions, but I want these functions to only interact with a single property of that class. class Foo { constructor() { this.$wrapper = $('<div>wrapper</div ...

Open the HTML document and access the file contents

I'm having trouble reading a text file from my computer onto a website. It works fine in Internet Explorer, but won't work in Chrome. I don't have much experience with HTML, so any help would be much appreciated! <html> <body> ...

Switching an image when hovering over another div - a simple tutorial

Currently, I am in the process of creating a product page for metal address numbers on a website. These numbers are available in four distinct colors: gold, chrome, black, and brown. My goal is to enable users to hover over a specific color div, prompting ...

"Step-by-step guide on showcasing a specific blog post using its unique identifier in an Angular/Express/MongoDB application

I'm struggling to figure out how to retrieve a single blog post by its ID, especially since I am new to this. Currently, my main blog application has an ng-repeat functionality that fetches all posts. What I really want is the ability to click on a p ...

What is the best way for me to make sure the element overflows properly?

How can I make the contents of the <div class="tags> element cause overflow so that one can scroll its contents instead of the element simply extending in height? I've experimented with different combinations of overflow-y: scroll and min- ...

What could be causing the issue with ng-include not functioning properly?

Issue with ng-include Organized Directory Structure : ssh_project --public ----templates ------header.html ------footer.html ----views ------index.html Here is the content of my index.html file <body> <h1>Hello</h1> <div ng ...

Having trouble locating and interacting with the textarea element in Salesforce using Selenium Webdriver

Encountering an issue with the Selenium Webdriver where it throws an error stating that the element is not visible and cannot be interacted with when attempting to access a textarea. 1. The textarea is located within a pop-up window, which can be accessed ...

User-Preferred Dark Mode Toggle Using Material-UI and Fallback Option

I am working on implementing a toggle for "dark mode" that is functioning well. However, I want the initial state to reflect the user's dark/light preference. The problem is that prefersDarkMode seems to be set to false when the page loads. It only c ...

Ways to confine the tabindex within a specific div container

I am currently working on identifying examples of bad accessibility practices. Specifically, I am focusing on issues related to Keyboard Focus. The first example I have encountered is the lack of visibility when trying to navigate through a set of buttons. ...

CSS navigation issue

When using the third example provided on this page: http://simple-navigation-demo.andischacke.com/ I encountered an issue where the main page would display an empty div on the left instead of the content filling the entire area. However, when navigating ...

I am encountering an issue with my PHP code that is causing an error

Whenever I try to submit my form, I keep encountering this error message. Can anyone offer some assistance with this issue? Error: Parse error: syntax error, unexpected '"', expecting T_STRING or T_VARIABLE or T_NUM_STRING in /home/u378761662/ ...

Why won't both routes for Sequelize model querying work simultaneously?

Currently, I am experimenting with different routes in Express while utilizing Sequelize to create my models. I have established two models that function independently of one another. However, I am aiming to have them both operational simultaneously. A sea ...