salep
salep

Reputation: 1380

jQuery prepend and fadeIn

When a user post a status, I show it at the top of the feed page. I want to add it a fadeIn effect, but the script I wrote hides all the updates and shows again. I want this apply to only the latest status.

What's wrong with it?

HTML

<div class="col-md-12" id="sharing">
</div>

JS

$("#sharenow").click(function () {
        var formData = {
            'text': $("#update-text").val()
        };

        $("#update-text").val('');

        $.ajax({
            type: 'POST',
            url: '/newstatus',
            data: formData,
            dataType: 'json',
            encode: true
        })

            .done(function (data) {
                if (data.success) {
                    $("#sharing").prepend('<div class="row posts">'+data.comment+'</div>').hide().fadeIn(1500);
                }
            });

    });
});

Upvotes: 1

Views: 1137

Answers (2)

enigma
enigma

Reputation: 3491

You want to use .prependTo()

$('<div class="row posts">'+data.comment+'</div>').prependTo("#sharing").hide().fadeIn(1500);

As a rule of thumb, JQuery always returns the wrapper of the first thing selected, so in this case you want it to return the new addition, not $("#sharing").

Upvotes: 3

lyosef
lyosef

Reputation: 6222

The jQuery element that returns from the "prepend" command is the $("#sharing") one, so all following methods operate on it (and not the added comment).

Try creating a variable holding the hidden comment jQuery, and separate your calls to a "prepend" call and after that a fadeIn call:

var comment=$('<div class="row posts">'+data.comment+'</div>').hide();  
$("#sharing").prepend(comment);
comment.fadeIn(1500);

Upvotes: 1

Related Questions