Question

I have a section of my form where a user can add additional fields. When "Add Fields" is clicked a space should be made below option1, then after a delay, the newly added field fades in. My field does not fade in, or slide down, and there is no delay. A space is made, and that's it. What am I doing wrong?

section of my form:

<div id="answers" style="display:none;">
    <div class="form-group" id="option1">
        <div class="col-xs-11 col-sm-9 col-md-6">
            <input class="form-control" id="answer" placeholder="Answer Option">
        </div>
        <div class="col-xs-1 col-sm-1 col-md-1" style="line-height:36px;">  <a href="" class="remove">Remove</a>

        </div>
    </div>
    <div>   <a href="" id="add">Add Field</a>

    </div>
</div>

My jQuery:

$("#add").on("click", function (event) {
    event.preventDefault();
    var clone = $("#answers div:first").clone()
        .css({
        opacity: 0
    });

    $("#answers div:last").before(clone)
    //(clone).insertBefore("#adding")
    .slideDown('fast')
        .delay(300)
        .animate({
        opacity: 1
    }, {
        queue: false,
        duration: 'fast'
    });
});
Was it helpful?

Solution

Your chaining is the issue: Try:

$("#answers div:first").clone().css({
         opacity: 0
     }).insertBefore("#answers div:last").slideDown('fast', function () {
         $(this).animate({
             opacity: 1
         });
     });
});

Fiddle

When you do $("#answers div:last").before(clone) it returns your div i.e the add button not the cloned element and i think you are giving a delay so that slide down happens completely before you animate opacity, you can achieve that using the complete callback syntax of slideDown.

Update based on your comment:

 $("#add").on("click", function (event) {
     event.preventDefault();
     $("#answers div:first").clone().css({
         opacity: 0,
         display:'none'
     }).insertBefore("#answers div:last").slideDown('slow').animate({
             opacity: 1
         });
 });

Fiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top