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

Reassigning Click Functionality in AJAX After Initial Use

Encountering an issue with a click event on an AJAX call. The AJAX calls are nested due to the click event occurring on a div that is not present until the first AJAX call is made. Essentially, I am fetching user comments from a database, and then there ar ...

What is the best way to retrieve the color of a WebElement when dealing with a complex CSS structure in Webdriver

I am currently trying to determine if the color of a specific page changes immediately after clicking on a button designed to alter the color of an element within that page. My goal is to extract the RGB value stated as rgb(183,168,168); in this particul ...

Triggering onClick without interfering with its populated variable

I'd like to add the following code snippet to my document: $('#myDiv).append("<div id='myDiv2' onclick="+extElementConfig.onClickDo+">Do</div>"); The code above uses an object with properties to populate the onClick attrib ...

Generating documents in Word or PDF format using PHP and Angular data

My goal is to generate a Word document using PHP for which I found a solution involving the use of headers. header("Content-type: application/vnd.ms-word"); header("Content-Disposition: attachment;Filename=output.doc"); Initially, this method worked well ...

Encountered an error while building CSS Modules for a Vue.js project

Working on a project in Vue.js, I decided to incorporate CSS modules for my local styles (for sass and scss). However, I continuously encounter a 'Failed to compile error' related to the CSS Loader validation process. Despite attempting various ...

Error: The reference to WEBGL has not been properly defined

Within my HTML, the code snippet below is causing an issue: if (WEBGL.isWebGLAvailable()==false) { document.body.appendChild(WEBGL.getWebGLErrorMessage()); } Upon running this code, the following error appears in the console: Uncaught ReferenceErr ...

Trouble with JavaScript confirm's OK button functionality in Internet Explorer 11

Having trouble with the OK button functionality on a JavaScript confirm popup in IE11. For one user, clicking OK doesn't work - nothing happens. It works for most other users though. Normally, clicking OK should close the popup and trigger the event h ...

Is there a way to retrieve nested data from a JSON API response?

Trying my hand at creating a basic CLI cryptocurrency tracker app. The app runs a successful API call and provides the following output: [ { exchange: 'binance', base: 'ADA', quote: 'BTC', price_quote: '0.000 ...

Expanding CSS styles on hover

When my mouse pointer moves out of the red color box, it still triggers the hover function. However, I only want the hover effect to work within the red color box and hide the menu when it's outside the box. This is the source code from JSfiddle: htt ...

I am having trouble with Popover and Tooltip not functioning properly in my browser

Today, I spent countless hours trying to implement popovers in my table to display additional information for each cell. However, I eventually discovered that the popovers do not seem to be functioning at all in my code. What could be causing this issue? D ...

Force the page to refresh if the user navigates back using the browser's back button

Similar Question: Cross-browser onload event and the Back button I am looking for a way to automatically refresh a view or page when a user navigates back to it using the browser's back button. Any suggestions? ...

The occurrence of an error is triggered by the Jquery.ajax()

Here's a useful link for you to try out: If you take a closer look, you'll see that it takes the $_GET['fname'] parameter and outputs the content I need. I made an attempt at solving this: $.ajax({ type: 'GET', url: ...

Is there a way to eliminate padding and increase the size of images in mobile view?

Over on my photography blog, I'm working on adjusting the padding within the blue box, increasing the size of my images, and eliminating hover effects for mobile views. Despite my efforts, the code I've implemented hasn't produced the desire ...

Secure user verification using session variable in the Express framework with NodeJs

Is it safe to use session variables for login persistence in the backend? What are the security implications and alternatives to consider? Technology Stack: Express (NodeJs) on the backend, MaterialUI (React) on the frontend I am seeking a straightforwa ...

Error: Cannot access 'addEventListener' property of null in Chrome Extension due to TypeError

I've been working on developing a chrome extension that autofills input forms in web pages. However, I encountered an error that says "cannot read properties of null." This issue arises when I try to add an event listener to a button in my code. The f ...

Meteor: Transforming MongoDB server logic for the client's use

Although I can successfully retrieve data from the meteor mongo terminal using this code, I am struggling to fetch data from the client side. I realize that the syntax for the client side is different, but being new to this environment, I am unsure of ho ...

The Unit Test for Angular NgRx is not passing as expected

I'm facing difficulties with my unit tests failing. How can I verify that my asynchronous condition is met after a store dispatch? There are 3 specific checks I want to perform: 1/ Ensure that my component is truthy after the dispatch (when the cond ...

What is the purpose of applying the two unique class names (root and disabled) to the DOM in order for it to function correctly?

When it comes to customizing components using material-ui, the process can be a bit tricky. Here's how you can do it: const styles = { root: { '&$disabled': { color: 'white', }, }, disabled: {}, // This is i ...

Guidelines for transferring data from a controller to jQuery within a CodeIgniter view

Currently, I am immersing myself in web programming through framework codeIgniter. My aim is to pass a value from a function within the controller to the query script located in the view file. Here's the snippet of code inside my controller: public f ...

What methods can be used to identify the pattern entered by the user for data types such as `Int`, `VarChar`, `

I have a dropdown menu containing data types. There is also a text box for entering Regex patterns. If "/test/" is entered in the textbox or "Int" is selected from the dropdown, then it's an incorrect pattern. If "/[0-9]/" is entered in the ...