Consider this function:
function hideElements( selector ) {
var number = $( selector ).length;
if ( number ) {
$( selector ).animate( { opacity: 0 }, 1000, function() {
*RETURN* number + " elements are now completely hidden.';
} );
} else return "No matching elements found";
}
var returnedMessage = hideElements( ".hideable-divs" );
The uppercase RETURN
is the callback's return and so it won't work; I just put it there to convey the idea. How can I make it so the hideElement
function returns something only after the animation is complete? Yes, whatever code that needs the returnedMessage
variable will have to wait (synchronously(?)) until the animation is complete. Thank you!
** EDIT ** This isn't a duplicate question but rather a very specific scenario I'm dealing with:
A third-party script uses a confirm
dialog to ask the user if they're sure they want to delete a div. If the user clicks OK, the element is removed instantly from the DOM.
My goal is to:
- Bypass the confirmation dialog so the user doesn't have to confirm.
- Animate the deletion so the user clearly sees it happening and, in case they clicked by accident, undo if necessary.
For this, I'm redeclaring window.confirm
like in the code sample below. (To eliminate any confusion, please note that this update changes the idea behind my original question and the code block I posted above.)
var clickTarget;
$( document ).on( 'mousedown', function( event ) {
clickTarget = event.target;
} );
window.confirm = function( message ) {
if ( message.indexOf( 'OK to delete' ) !== -1 ) {
var $element = $( clickTarget ).parent();
$element.animate( { height: 0 }, 1000, 'swing', function() {} );
return true; // the 3rd party script receives this confirmation asynchronously and removes $element before it has a chance to be animated.
} else return confirm( message );
};
At the moment I'm achieving the effect by creating a clone and animating that instead of the actual element to be deleted. But this is rather "dirty" and I was wondering if there's a "cleaner" way to do it. Thanks!