Laurynas Tamulevičius
Laurynas Tamulevičius

Reputation: 1579

How to fadeIn parent div along with the child?

Currently I have a div container #songs with a list which is wrapped in parent div #guts. I am appending new list elements using jQuery appendTo() method. On append I use fadeIn() method, however that only animates the #songs div.

My question is, how can I animate the parent div at the same time so that once the new element is added the parent div #guts extends smoothly?

This is the example code:

HTML:

<div class="jumbotron" id="guts">
    <button type="button" id="add-btn">Add to playlist</button>
    <div id="songs">
        <ul>
            <li>Some list element</li>
        </ul>
    </div>
</div>

JS:

$(document).ready(function () {
    $("#add-btn").click(function(){
        var new_el = "<li>New element</li>";
        $(new_el).appendTo("#songs").hide().fadeIn();
    });
});

CSS:

.jumbotron {
    padding-top: 30px;
    padding-bottom: 30px;
    margin-bottom: 30px;
    background-color: #eee;
}

And fiddle:

Upvotes: 0

Views: 241

Answers (1)

Matt
Matt

Reputation: 1570

Something like this should do it.

$(document).ready(function () {
    $("#add-btn").click(function(){
        var new_el = "<li style=margin-bottom:-20px; opacity:0;>New element</li>";
        $(new_el).appendTo("#songs").animate({'margin-bottom':'0', 'opacity':'1'}, 400);
    });
});

And CSS

.jumbotron {
padding-top: 30px;
padding-bottom: 30px;
margin-bottom: 30px;
background-color: #eee;
}
#songs li:not(:first-of-type) {
  opacity: 0
}    

Upvotes: 3

Related Questions