I'm creating a jquery animation and weirdly, when I append a new paragraph, it appends it twice, the problem only happens when 2 previous paragraphs are appended, probably that's a jQuery bug.. otherwise, I hope someone can help me.
HTML:
<body>
<div id="element">
</div>
</body>
JavaScript:
$(function() {
animation();
});
function animation()
{
$('<p id="p1">paragraph 1</p>').appendTo('#element');
$('<p id="p2">paragraph 2</p>').appendTo('#element');
$('#p1, #p2').fadeOut(600, function(){
$('#p1, #p2').remove();
var $p3 = $('<p>paragraph 3 </p>').appendTo('#element');
});
}
The problem is with "paragraph 3" that is appended twice! You can run the code here: http://jsfiddle.net/jonah13/QLM2s/
Thanks, Younes
Create a paragraph element with some text and append it to the end of the document body using jQuery. JavaScript Code : $( "p" ). add( "<span>Exercises</span>" ).
jQuery append() MethodThe append() method inserts specified content at the end of the selected elements. Tip: To insert content at the beginning of the selected elements, use the prepend() method.
It's easy to append text into this div using append() as shown below. It will append the text directly before the closing </div> tag. This example would add "this text was appended" to the above div: $('#example').
I don't know why other answers that identified the problem were down-voted, since they identified the problem.
Here is the code to fix it. Note from the jQuery docs, that as of jQuery 1.6 (which I assume you're using since the jsFiddle was using 1.7.2) you can use .promise()
:
As of jQuery 1.6, the
.promise()
method can be used in conjunction with thedeferred.done()
method to execute a single callback for the animation as a whole when all matching elements have completed their animations.
I've updated your fiddle:
$(function() {
animation();
});
function animation()
{
$('<p id="p1">paragraph 1</p>').appendTo('#element');
$('<p id="p2">paragraph 2</p>').appendTo('#element');
$('#p1, #p2')
.fadeOut(600)
.promise().done(function() {
$('#p1, #p2').remove();
var $p3 = $('<p>paragraph 3 </p>').appendTo('#element');
});
}
The function provided to fadeOut()
is fired once per element which matches the selector. Since the selector returns two elements it is fired twice, thus appending two paragraphs.
Modified example here: http://jsfiddle.net/QLM2s/1/
The problem is where fade out paragraphs 1 and 2: jQuery is executing the code inside the fade-out function for every selector you give it (in this case, two paragraphs so two appends).
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