Reputation:
I am using to jQuery to dynamically add a form input to an ordered list using append(), which works great:
$newItem = $('input[type=text]').val();
$("#toDoList").append('<li class="listItem">' + $newItem + '<div class="delete">X</div></li>');
The new list item appears without problems.
However, I would like to use a fadeIn() effect for new items that are added, which I don't get working.
I tried the following without success:
$("#toDoList").append('<li class="listItem">' + $newItem + '<div class="delete">X</div></li>').fadeIn('slow');
Any idea what is wrong?
Upvotes: 2
Views: 1012
Reputation: 1684
fadeIn
is not working because when the new content is appended, it is automatically displayed normally. If you set the style of the appended attribute to display: none
either inline as in my example or in CSS, and then call fadeIn
it will work. See snippet below:
var newItem = $('input[type=text]').val();
$("#toDoList").append('<li style="display: none;" class="listItem">' + newItem + '<div class="delete">X</div></li>');
$("li").fadeIn("slow");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="test">
<ul id="toDoList">
</ul>
Upvotes: 0
Reputation: 337600
The issue is because you first need to hide the element, as it's already visible when appended so fadeIn
appears to do nothing. Try this:
var $newItem = 'Foo';
$('<li class="listItem">' + $newItem + '<div class="delete">X</div></li>')
.hide()
.appendTo('#toDoList')
.fadeIn('slow');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="toDoList"></ul>
Upvotes: 3