Using jQuery to select and animate several elements simultaneously without repeating the animation

Issue Summary (Fiddle):

I'm trying to make all elements fade out simultaneously when clicked, but the current code causes the target to trigger three times resulting in three alert() calls. I want them to fade together without using a wrapper element.

How can I make sure that the actions inside fadeOut() completion only execute once?

Code Snippet:

HTML:

<div class="things">
    <div id="one"></div>
</div>
<div class="things">
    <div id="two"></div>
</div>
<div class="things">
    <div id="three"></div>
</div>

JavaScript:

var triggerCount = 0;
$('.things').mousedown(function() {
    $('.things').fadeOut(2000, function() {
        triggerCount++;
        alert('fading '+triggerCount+' time(s)');
    });
});

Answer №1

Take a look at this insightful answer provided here: How to Hide multiple elements with jQuery and receive one callback. If you prefer not to utilize jQuery.when(), it is suggested to create a wrapper element.

Instructions on using jQuery.when():

$.when($('.things').fadeOut(250)).then(function() {
    // carry out an action
    alert('fading');
});

Answer №2

Utilize the $.when() method:

This method offers a way to run callback functions based on one or more objects, typically deferred objects representing asynchronous events

var triggerCount = 0;
$('.things').mousedown(function () {
    $.when($('.things').fadeOut(2000)).then(function () {
        triggerCount++;
        alert('fading '+triggerCount+' time(s)');
    });
});

Check out the Updated Fiddle here

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

Assigning the "checked" attribute to the checkbox based on its "value" parameter

Within a .cshtml form, I have a checkbox field that has the following attributes: @Html.CheckBox("InFooter", new { @class = "form-control", @id = "edit_rssFeed_InFooter" }) Currently, I am using ajax to set the value of the "value" attribute for this che ...

Searching for ways to filter out specific tags using regular expressions

Can anyone provide a quick solution to help me with this issue? I am trying to remove all html tags from a string, except for the ones specified in a whitelist (variable). This is my current code: whitelist = 'p|br|ul|li|strike|em|strong|a', ...

What Could Be Causing My Webfonts to Be Inaccessible on Windows Devices and iPhones?

I recently created a simple holding page on www.tomrankinmusic.com The Webfonts I embedded in the page display correctly in the latest versions of Firefox, Safari, and Chrome on Mac OSX Lion 10.7.4 but do not show up in Chrome and IE6 on Windows XP Pro, d ...

What steps can you take to convert your current menu into a responsive design?

I am currently developing a website using PHP, HTML, and CSS. The site is not responsive, and I want to make the menu responsive. My global navigation and admin interface are not adapting properly as they are designed using tables. Is there a method I can ...

How can you retrieve the property value from an object stored in a Set?

Consider this scenario: SomeItem represents the model for an object (which could be modeled as an interface in Typescript or as an imaginary item with the form of SomeItem in untyped land). Let's say we have a Set: mySet = new Set([{item: SomeItem, s ...

Executing Bower installation within a corporate proxy network

Encountering Error : ECONNREFUSED Request to https://bower.herokuapp.com/packages/bootstrap-datepicker failed: connect ECONNREFUSED while attempting Bower Install from Package Manager Console. I came across suggestions in a different discussion on how to ...

What is the reason behind the significant 80% reduction in PNG files by grunt-contrib-imagemin compared to the minimal reduction of less than 0.1%

Just getting started with Grunt here. Recently, I've been experimenting with grunt-contrib-imagemin. When it comes to compressing PNG files, it does an impressive job. It typically reduces the size by around 80%. However, I'm finding that the ...

I need to find a way to transfer user input data from the frontend to ExpressJS in order to make an API call using an endpoint

Within my perspective, there is a text box where users can input values. Leveraging jquery, I retrieved the user's value and now aim to transfer it from my jquery file to the express module in app.js. Any ideas on how to best approach this? ...

Avoid generating `.d.ts` definition files during the onstorybook build process in a Vite React library project

I am currently developing a component library using react and typescript. I have integrated Vite into my workflow, and every time I build Storybook, the dts plugin is triggered. This has two undesired effects: It generates numerous unnecessary folders an ...

The measure of the leaflet map's vertical dimension in a Shiny module application

I'm facing an issue while trying to incorporate my small app as a module within my larger app. Everything seems to be working fine except for the height of the leaflet map. In the standalone app, I had: ui <- fluidPage( tags$style(type = "te ...

Displaying the numeric value from a MySQL database in a textbox

In my code, I utilize the following segment to populate a database table where each row contains a button with the label "Load". while($row=mysqli_fetch_array($result)) { echo" <tr id='rowNum'> <td >".$row['No.'] ...

Issue with Magento: Unable to execute dataflow profiles due to Ajax Error (Uncaught TypeError: e is not a function)

Whenever I try to execute a dataflow profile in Magento, the following series of events unfold: The CSV file is uploaded successfully X rows are found A message displays: Starting ... :: saveRow (handler-method) However, a JavaScript error interrupts th ...

Add a new external link to the Jquery Mobile webpage

Hello, I'm primarily a designer and my programming skills are quite limited. I am attempting to embed an external page into my jQuery Mobile webpage using external links, which works well in Safari. However, the issue arises when I save the web app t ...

Switch up the animation based on the state in AngularJS

In my AngularJS application, I have implemented CSS animations for transitioning between states. The animations involve sliding content from left to right with specific timings and transforms. .content.ng-enter, .content.ng-leave { -webkit-animation-t ...

Using the i18next Module for Localization in ExpressJS and Front-End Development

I am currently integrating the i18next module into my NodeJs/ExpressJS web application. All the translation files are stored in the /locales directory. According to information from i18next.com, it can also be utilized on the client side. <script typ ...

The jsPDF tool captures only the visible frame in a screenshot instead of printing the entire content on the screen

Recently, I integrated the jsPDF npm module into my Angular application to convert HTML to PDF. However, I encountered an issue where printing a website page to PDF only captures a screenshot of the visible area in Firefox and Chrome, as well as in Interne ...

Testing with mount in React Enzyme, the setState method does not function correctly

I've been experimenting with testing this code block in my React App using Jest and Enzyme: openDeleteUserModal = ({ row }: { row: IUser | null }): any => ( event: React.SyntheticEvent ): void => { if (event) event.preventDefault(); ...

Is it possible to line up Ajax request in Javascript?

I am seeking a way to schedule an Ajax request to occur every second. The code I currently have in place functions flawlessly. window.onload = function () { setTimeout(doStuff, 1000); // Wait before continuing } function doStuff() { ...

What could be causing the lack of data with 'react-hook-form'?

I have encountered an issue while working with react-native and using 'react-hook-forms' for creating dynamic forms. The problem is that the data object returned is empty, even though it should contain the values entered in the input fields. When ...

What could be causing my webpage content to be partially hidden by my CSS menu?

I am currently working on my website which features a CSS menu with my website logo, a text box, and a dropdown. Additionally, I have created a login form using a table like the one shown below. <p>&nbsp;</p><table width="40%" border="0 ...