How to FadeIn an Appended Div without Fading In All Divs displayed?
Ok. I know this is probably pretty simple, but I am having a difficult time with it :/.
I am trying to make Divs FadeIn when they are appended 开发者_StackOverflow中文版to a parent div. My problem is, that when new divs are appended, all of them fade in.:
<div id="click">Click Me</div>
<div id="textResp"></div>
$('#click').live('click',function() {
$('#textResp').append("<div id='hi' class='eventdiv'>hello</div>").hide().fadeIn(3000);
});
I know that it is because the fadeIn(3000) is attached to the parent because it is starting with $('#textResp'), but how do you attach this to the created object?
Thanks,
Taylor
Simply create your element via a jQuery and call the hide()
and fadeIn()
methods on that object and not #textResp
$('#click').live('click', function() {
var $d = $("<div id='hi' class='eventdiv'>hello</div>").hide().fadeIn(3000);
$('#textResp').append($d)
});
Example on jsfiddle
Side note, I am sure this is just a generalized example, but the id should be unique.
$('#click').live('click', function() {
var $d = $("<div/>", {
id: 'hi' + $('#textResp').children().length, //generate a unique id
class: 'eventdiv',
html: 'hello'
}).hide().fadeIn(3000);
$('#textResp').append($d);
});
Example on jsfiddle
Two problems:
First, all your appended divs have the same id, 'hi'. As separate elements they need distinct ids.
Second, you're using fadeIn(3000) on $('#textResp'), not the appended div. Try something like this:
$('#textResp').append("<div class='eventdiv'>hello</div>");
$('#textResp div:last-child').hide().fadeIn(3000);
This should do what you want:
<script type="text/javascript">
var count=1;
$('#click').live('click',function() {
var id='hi'+count,
elt=$('<div id="'+id+'" class="eventdiv">hello</div>');
$('#textResp').append(elt.hide().fadeIn(3000));
count++;
});
</script>
Try reversing the order of your chain. I'd do it like this...
$("<div id='hi' class='eventdiv'>hello</div>").appendTo("#textResp").hide().fadeIn(3000);
That way, when you "fadeIn", you're still in the context of the newly created div. Based on your question, I'm assuming this is the desired behavior. It's a lot more straightforward than the other 2 answers I've observed.
Hide it from the beginning and then just show the last one
$('#click').live('click',function() {
$('#textResp').append("<div style='display: none' class='eventdiv'>hello </div>");
$('#textResp div:last-child').fadeIn(1000);
});
demo: http://jsfiddle.net/xp6fU/
精彩评论