What is the proper method for utilizing the .done or .complete functions in conjunction with .toggle in jQuery?

I am struggling to understand the proper usage of .complete or .done after .toggle in jQuery. My goal is to have the button's text change after the toggle animation finishes, but I'm not sure if I'm chaining them correctly. The jQuery documentation only mentions these as "options" without providing examples on how to use them. Can anyone clarify how to properly utilize these options? Is it not done as shown below?

$(document).on("click", "#new-contact-btn", function(event){
    event.preventDefault();

    $("#new-contact-row").toggle(200).complete(function(){  

      if ( $("#new-contact-row").is(":visible") ) {
        $(this).text("Cancel");
      } else {
        $(this).text("+ Add New Contact");
      }
    });
});

The code snippet above doesn't work as expected, as the button text fails to change upon clicking.

Answer №1

The function toggle() does not return a promise or deferred object, so calling complete() on it will not have any effect.

To make it work, you should use the second argument of the method call, which is the callback function. If you provide a function as the callback, it will be executed when the animation completes. Keep in mind that within this function, 'this' refers to the row and not the button, so you need to store a reference to the button in a variable. Here is an example:

$(document).on('click', '#new-contact-button', function(event) {
  event.preventDefault();

  $('#new-contact-row').toggle(200, function() {
    $('#new-contact-button').text($(this).is(":visible") ? "Cancel" : "+ Add New Contact");
  });
});
div { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="new-contact-row">Contact Row</div>
<button id="new-contact-button">+ Add New Contact</button>

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

Executing animation after the completion of a transition

Is there a way to synchronize the bounce animation with the scaling of an object, so that it appears smooth and fluid? I've tried using the animation delay property along with the transition delay property, but they don't seem to align correctly. ...

Filtering input based on its occurrence rate (enable/disable debounce)

Utilizing node on a raspberry pi and the module onoff to capture input. I am interested in running function B only if function A is triggered twice within one minute. var gpio = require('onoff').Gpio; var sensor = new gpio(7, 'in', &ap ...

Having trouble accessing JSON file again: "Encountered unexpected end of input error"

I have set up a cron-based scheduler to periodically retrieve JSON data from an external API every 2 minutes. The process involves writing the data to a file, reading it, cleaning it, and then storing it in a MongoDB collection. Everything works smoothly o ...

How to utilize a PHP array within a Vue.js template

I have been exploring the realms of Laravel and vue.js recently and have encountered a challenge. Within my Laravel model, I have a PHP method that retrieves data from a database and organizes it into objects stored in an array. Now, my goal is to access t ...

How can I retrieve the child of a specific selector using jQuery?

I'm having trouble articulating my issue clearly. I need to retrieve the child of a tag that I previously selected. Here's a simple code example: This is the HTML code: <div class="inner"> <div class="box"> <a href="yagh ...

Checking for valid zip code using a regular expression in JavaScript

Thank you for the suggestions, everyone. I have made some modifications to the script based on your advice and it appears to be functioning correctly now. <script src="jquery-1.4.2.min.js" type="text/javascript"></script> <script> $ ...

I'm having trouble getting the aggregation of a child collection to work properly in MongoDB when attempting to apply the $count

Could someone help me troubleshoot my aggregate query? I'm trying to sum the count values for each beacon, but it keeps returning 0. Please let me know if you spot any mistakes in the query. Sample Data [ { ...

Localhost is unable to process AngularJS routes containing a dot in the URL

When using the route provider and setting this specific route: .when('/:name/:id', { It successfully navigates to my desired path and executes the code when I enter: https://localhost.myapp.com:9000/Paul/123 However, it fails to work with this ...

Wrap the json response in HTML elements

I'm currently learning about AJAX, and I've encountered a major issue that I can't seem to resolve. I pass several variables to PHP, perform various checks there, and then return string values to AJAX. Strangely, I am able to display these r ...

Is there a Wordpress floating bar similar to the one seen on 9gag?

After browsing through some posts on stackoverflow, I noticed that my website is not responding as expected. You can check out my site here: To troubleshoot, you can examine the source code and utilize Firebug to inspect the css and javascript being used ...

Make sure to wait for the scrollTo function to finish before executing any other commands

I have a sleek scrolling directive in my AngularJS app that automatically scrolls to the bottom of the page. I want this command to execute only after the scrolling has completed. Currently, I trigger the scroll function and then use $('#comment-input ...

Looking for a seamless way to convert jsp code to html using sightly in AEM 6.1?

I need help transforming JSP code to HTML using Sightly in AEM. In the JSP code, we have a scriptlet that stores a value from the dialog into a JSP variable called "coltype" using the code pageContext.setAttribute("coltype", xssAPI.filterHTML(properties. ...

The overall outcome determined by the score in JavaScript

Currently, I am working with a dataset where each person is matched with specific shopping items they have purchased. For instance, Joe bought Apples and Grapes. To gather this information, individuals need to indicate whether they have made a purchase. I ...

Confirm the presence of Cookie and save the data

I'm a beginner in the world of Javascript and Ajax, attempting to save a user's name using cookies. I have created a form where users can input their first name (identified by id = firstName). My goal is to remember this information so that the n ...

Is there a point in bundling NPM packages if they are ultimately going to be bundled by the project

I'm in the process of creating a TypeScript package for publication on NPM. My plan is to utilize this package in upcoming web development endeavors, most likely utilizing Vite. As I look ahead to constructing a future website with this module, I am c ...

Next.js is constantly encountering an issue where it throws an error stating "params

I've managed to establish a successful connection between my custom server using Node.js and Express.js with Next.js. The issue I'm facing is when trying to fetch a specific car by its id upon clicking it among other cars, as I keep encountering ...

Progressing with Jquery AJAX sequentially

I'm attempting to send two ajax requests in succession. My plan was to utilize the ajax success() function for this task: $.ajax({ ... success: function() { //perform the second ajax request here } }); The issue is that the first ...

Tips for updating VUE's main.js file to incorporate the routers/index.js configuration

What is the reason for the difference in syntax between the VUE UI main.js code generated by CLI/3 and the older version, and how does it function? What are the various components of the new syntax and how do they work? sync(store, router) // for vuex-rou ...

Tap to reveal additional information with the power of Jquery and ajax

I have a question regarding the popup slide functionality. I would like to achieve the following: Currently, I am using the following code to display post details upon clicking: function getPostDetails(id){ var infoBox = document.getElementById("in ...

Implementing a New Port Number on a ReactJs Local Server Every Time

As a newcomer to ReactJS, I recently encountered an issue while working on a project that puzzled me. Every time I shut down my local server and try to relaunch the app in the browser using npm start, it fails to restart on the same port. Instead, I have ...