Reputation: 75
I created a function that adds text to an element called #textBox. I want the text to fade in the box so, here is my code.
var addText_3 = function(text) {
$("#textBox").append("<p><i>" + text + "</i></p>").hide().fadeIn(500);
};
So, my function appends to text and hides it so it can fade in. However, I just want the appended element to fade in. When I try this function, all of the other text in the element also fade. Is there a way to only make the element I am appending to fade in?
Upvotes: 0
Views: 1361
Reputation: 5454
This one's my personal pref
var text = 'asdfasdfasdf';
$("<p><i>" + text + "</i></p>").fadeIn(500).appendTo($('#textBox'));
Upvotes: 0
Reputation: 10698
The chaining of function does not return what you expect : it returns #textBox
while you thought it'll returns your freshly created text node.
So, you have to call both the hide()
and fadeIn()
functions on your text node instead.
appendTo()
is the function you'd rather use as it returns the caller (call it on your new node).
Example (with jQuery's clean node creation) :
var addText_3 = function(text) {
var text_node = $("<p>").append($("<i>", {html: text})).hide(); //Can use text instead of html
text_node.appendTo("#textBox").fadeIn(500);
};
Upvotes: 1
Reputation: 18891
$("<p><i>" + text + "</i></p>").appendTo("#textbox").hide().fadeIn(500);
Create the new element, append it to #textbox
, and fade it in.
var text = 'Stack Overflow';
$("<p><i>" + text + "</i></p>").appendTo("#textbox").hide().fadeIn(500);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="textbox">Some text</div>
Upvotes: 1