-1

Underneath you will find my original code:

function refreshChat() {
  var id = "'.$convers_id.'";
  var receiver = "'.$system->getFirstName($second_user->full_name).'";
  $.get("'.$system->getDomain().'/ajax/refreshChat.php?id=" + id + "&receiver=" + receiver, function(data) {
      $("#messages").html(data);
      $(".conversation-message-list").getNiceScroll(0).scrollTop($(".conversation-content").height(), -1);

    setTimeout(refreshChat, 3000);
  });
}

function sendMessage() {
  var user2 = "'.$user2.'";
  var message = $("#message");
    if(message.val() != "" && message.val() != " ") {
    $.get("'.$system->getDomain().'/ajax/sendMessage.php?id="+user2+"&msg="+encodeURIComponent(message.val()), function(data) {
    $("#messages").html(data);
    message.val("");
    });
    }
}
$(document).keypress(function(e) {
        if(e.which == 13) {
            sendMessage();   
        }
    });
        function appendToMessage(str) {
var message = $("#message");
message.val(message.val()+" "+str);
$("#emoticonList").modal("hide");
}

What i am trying to is change the interval based on the height of the scroller (or the position), because every time it runs the refreshChat function, it pushes the scroller back down, which makes it impossible to scroll the chat.

I have already tried changing:

window.setInterval(function(){
  refreshChat();
}, 1000);

To:

    if ($(window).scrollTop() > 200) {
window.setInterval(function(){
  refreshChat();
}, 100000000000);
} else {
    window.setInterval(function(){
  refreshChat();
}, 1000);
}

But this breaks the script. I would like to thank everybody beforehand for taking the efford on helping me solve my problem.

NOTE: I HAVE EDITED MY ORIGINAL CODE BASED ON MPLUNGJAN'S SUGGESTION

But how can i append a new message inside the chatscreen as suggested?

HTML:

<div class="conversation-message-list" onclick="hideEmoticons()">

                            <?php if ($user->expire == NULL){ ?>
                            <!--geen abbo-->
                            <div class="i-info-msg text-center" style="padding-top:15%;"><div class="pass-frac-item"><p class="title">Je hebt een nieuw bericht ontvangen!<span class="arrow"></span></p></div>
        <p>Zien wie jou een bericht heeft gestuurd en antwoorden? Neem nu een Membership!</p>
        <p>Maak ook gebruik van andere Upgrades, zoals zonder reclame surfen, anoniem profielen bekijken of jezelf in de spotlight plaatsen!</p>

        <a class="i-button-14 i-button-bg-1" href="<?=$system->getDomain()?>/memberships.php">Neem een membership!</a>
    </div>
                            <!--/geen abbo-->
                            <? } else { ?>
                            <!--wel abbo-->
                                <div class="conversation-content" id="messages">
                                    <?php
                                    if($messages->num_rows >= 1) { 
                                        while($message = $messages->fetch_object()) { 
                                            $sender = $system->getUserInfo($message->sender_id);
                                            ?>
                                            <div class="row">
                                                <div class="conversation-message pull-left">
                                                    <div class="pull-left">
                                                        <img src="<?=$system->getProfilePicture($sender)?>" class="img-circle pull-left" style="height:50px;width:50px;">
                                                    </div>
                                                    <div class="well bg-grey pull-left emoticon-small">
                                                        <?php
                                                        if($message->is_sticker == 0) {
                                                            $message->message = $system->secureField($system->smart_wordwrap($message->message));
                                                            echo Emojione\Emojione::shortnameToImage($message->message);
                                                        } else {
                                                            $sticker = $db->query("SELECT * FROM stickers WHERE id='".$message->sticker_id."'");
                                                            $sticker = $sticker->fetch_object();
                                                            echo '<img src="'.$system->getDomain().'/img/stickers/'.$sticker->pack_id.'/'.$sticker->path.'" style="height:80px;width:80px">';
                                                        }
                                                        ?>

                                                    </div>
                                                </div>
                                            </div>
                                            <? } ?>
                                            <!--/wel abbo-->
                                            <? 
                                        } 
                                    }
                                    ?>
                                </div>
                            </div>

                            <div class="col-lg-12 col-md-12 col-sm-12">
                                <div class="conversation-input" style="position:static;">
                                    <div class="row">
                                        <div class="input-group message-input">
                   <?php if((!isset($blocked_msg))&&($user->expire != NULL)) {?>                     
                                            <input type="text" id="message" placeholder="<?=$lang["Enter_Message"]?>" class="form-control input-lg message-input no-border" required>
                                            <span class="input-group-btn">

                                                <a href="#" class="btn btn-default" data-toggle="modal" data-target="#send-gift"><i class="fa fa-fw fa-gift"></i></a>
                                            </span>
                         <?php } if(isset($blocked_msg)) { ?>
                         <input type="text" id="message" placeholder="JE BENT GEBLOKKEERD DOOR DEZE GEBRUIKER." class="form-control input-lg message-input no-border" required>
                        <?php } ?>

                                        </div>
                                    </div>
                                </div>
                            </div>
Aurora
  • 725
  • 1
  • 8
  • 17
  • don't forget to call `clearInterval`~ – Daniel A. White Jun 19 '16 at 13:21
  • Just scroll to bottom instead !!! – mplungjan Jun 19 '16 at 13:21
  • @mplungjan Thank you for teaching me something new. Underneath i have added the complete script: (i wish enter wont add a comment... i will edit my question so i can add more code – Aurora Jun 19 '16 at 13:34
  • Is this what you look for?: [scroll at bottom like in a chat app](http://stackoverflow.com/questions/34213227/scrollable-div-to-stick-to-bottom-when-outer-div-changes-in-size/34330934#34330934) – Asons Jun 19 '16 at 13:34
  • `$("#messages").append(data);` – mplungjan Jun 19 '16 at 14:50
  • @mplungjan First of all thank you again for your awnser, i'm pretty new at javascript and i have been trying multiple variations to get it working. But i have no idea how i should use `$("#messages").append(data);`. I have also tried removing `setTimeout(refreshChat, 3000);` (because it prevents scrolling) and made a callback. But everything i have tried, doesnt seem to get it working – Aurora Jun 19 '16 at 16:58
  • I cannot help you more since I do not know what `$.get("'.$system->getDomain().'/ajax/refreshChat.php?id=" + id + "&receiver=" + receiver` returns. If that only returns the last entry, then my code should work also assuming `$(".conversation-message-list").getNiceScroll(0).scrollTop($(".conversation-content").height(), -1);` scrolls to the bottom of the chat. And if you want it to update you need to call it again and again. If the – mplungjan Jun 19 '16 at 17:14
  • @mplungjan Your assumtions are 100% correct. refreshChat returns the complete chat, so it always includes the last sent message. Your next assumtion is also correct. `$(".conversation-message-list").getNiceScroll(0).scrollTop($(".conversation-con‌​tent").height(), -1);` scrolls back to the bottom. i have also tried calling it again and again by making a callback and a prommisses in the sendMessage function. – Aurora Jun 19 '16 at 17:17
  • then my first example should work. Any errors? I could think that the data with ".conversation-message-list" is in the data? Then perhaps `$(".conversation-message-list").getNiceScroll(0).scrollTop($(".conversation-content").height(), -1);` does not work properly. If you have errors in the console, the whole thing could fail. – mplungjan Jun 19 '16 at 17:23
  • @mplungjan error reporting showed no errors at all. i will edit my question again and i will add the html. Maybe the fault lies there.. – Aurora Jun 19 '16 at 17:50

1 Answers1

1

You should not use setInterval on AJAX. Instead use setTimeout from inside the success and then scroll to bottom each time - assuming that is what the getNiceScroll does, you can do this:

function refreshChat() {
  var id = "'.$convers_id.'";
  var receiver = "'.$system->getFirstName($second_user->full_name).'";
  $.get("'.$system->getDomain().'/ajax/refreshChat.php?id=" + id + "&receiver=" + receiver, function(data) {
    $("#messages").html(data);
    $(".conversation-message-list").getNiceScroll(0).scrollTop($(".conversation-content").height(), -1);
    setTimeout(refreshChat, 3000);
  });
}

Also do you need to send the complete chat? Why not just append new messages if any. Then you can test to see if there is something new and not do anything if not:

$("#messages").append(data);
mplungjan
  • 169,008
  • 28
  • 173
  • 236