In jQuery, can the empty() method be given a duration, such that the object fades to empty over a period of time (for example, 500 milliseconds)?
Here is the current code:
$('#object_to_be_emptied').empty();
The empty() method removes all child nodes and content from the selected elements. Note: This method does not remove the element itself, or its attributes. Tip: To remove the elements without removing data and events, use the detach() method. Tip: To remove the elements and its data and events, use the remove() method.
remove() – Removes all child elements with selected element. In this method you can restore all data but not event handlers of removed elements from the DOM. All data and events related with elements will be removed. empty() – Removes all content and child elements from the selected element.
How to check if element is empty using jQuery? You can use jQuery is() and :empty Selector together to check whether elements is empty or not before performing some action on that element.
length === 0) is indeed checking if an object is Empty.
The other two answers suggest using $('#object_to_be_emptied').children().fadeOut()
, but it is actually a bad idea to use .children()
because this will cause an animation to be applied to each of the child elements within your containing element (killing performance), and therefore execute the animation complete callback once for each element within object_to_be_emptied
. With more than just a couple of elements, this will turn into a real problem.
Instead, just apply the animation to the containing element, remembering to call .fadeIn()
after you've repopulated it and want to show it again.
$('#object_to_be_emptied').fadeOut(500, function() {
$(this).empty();
});
Also note that I've used this
in the callback function – jQuery sets this
to be the DOM element which is the target of the callback function; in this case, object_to_be_emptied
. Using this
saves some typing and makes code changes down the line easier.
No. Fade the content out, then empty it when the fade is complete.
$('#object_to_be_emptied').children().fadeOut(500, function() {
$('#object_to_be_emptied').empty();
});
This code unfortunately calls empty
as many times as there are elements under #object_to_be_emptied
. If you are using jQuery > 1.6, you can get round this with the $.Deferred
support for animations:
$('#object_to_be_emptied').children().fadeOut(500).promise().then(function() {
$('#object_to_be_emptied').empty();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With