Toma Tomov
Toma Tomov

Reputation: 1674

jQuery scrollTop doesn't work on dynamically created textarea

I have text area which is playing the role of chat. I tried to make it stay in the bottom on every new message but without success. What i did is :

var chatBox = $('.chat-box');
var body = $('body');
var chatContent = $('<textarea>', {
    rows : 11,
    "class" : 'chat-content',
    placeholder : 'Find your friens here .. ',
    readonly : true,
    id : 'cont'
});

//load last 10 messages on ready
$.ajax({
    method : 'POST',
    url : '../site/load-messages',
    dataType : 'json',
    success : function (data) {
        $.each(data.reverse(), function (key, value) {
            chatContent.val(chatContent.val() + value.message_author + " : " + value.message_content + '\n');
        });
    }
});

var chatMessage = $('<input>', {
    type : 'text',
    "class" : 'chat-message',
    id : 'chat-message'
});

var chatButton = $('<input>', {
    type : 'button',
    value : 'Send',
    "class" : 'chat-button',
    id : 'chat-button'
});

chatBox.hover(function () {
    $(this).animate({height : '300px'}, 'slow');
    chatBox.append(chatContent)
        .append(chatMessage)
        .append(chatButton);
}, function () {
    $(this).animate({height : '40px'}, 'slow');
});

body.keypress(function (e) {
    if(e.which == 13)
    {
        return sendMessage();
    }
});

body.on('click', '#chat-button', function () {
    return sendMessage();
});

function sendMessage() {
    var message = $('#chat-message').val();
    var chat = $('#cont');
    $.ajax({
        method : 'POST',
        url : '../site/add-message?message=' + message,
        dataType : 'json',
        success : function ( data ) {
            chat.val(chat.val() + data.message_author + ' : ' + data.message_content + '\n');
            $('#chat-message').val('');
            chat.scrollTop = chat.scrollHeight;
        }
    }) ;
}

chat is the text area which is dynamically created. Is it because of that my scrolling don't work? Or maybe i am doing it wrong? Appreciating every advice!

Upvotes: 0

Views: 271

Answers (1)

Guillaume
Guillaume

Reputation: 1062

Try by replacing chat.scrollTop = chat.scrollHeight; by chat.scrollTop(chat.prop('scrollHeight') - chat.height());

Upvotes: 1

Related Questions