-1

I have the following script which fetches, displays messages in a personal chat between two users. It's working but every time setTimeout is called it is jumping to the top of the page. I need the page to stay exactly where it is. Can you help?

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
    
    function update()
    {
     $.get("serve.php?trade_id=<?php echo $_GET[id]; ?>", {}, function(data) { $("#trade-messages").append(data); } );
     
     setTimeout("update()", 1000);
      
      
    }
     
    $(document).ready (
     function()
     {
      update();
      $("#sendmessage").click(
      function() {
       $.get("serve.php?from=<?php echo $_SESSION['id']; ?>&to=<?php echo $trading_with; ?>&trade_id=<?php echo $_GET['id']; ?>", 
       { message: $("#message").val() },
       function(data) {
         
        $("#trade-messages").append(data);
        $("#message").val("");
       }
      );
      }
      );
     }
    );
     
    </script>
    
    <div class="trade-messages-container">
     <div id="trade-messages"></div>
    </div>
    <br style="clear: both" />
    <textarea name="message" id="message" rows="4" style="width:100%;"></textarea><br />
    <button type="submit" id="sendmessage" style="float: right;">Send</button>

Thanks in advance

Hitesh Tripathi
  • 856
  • 1
  • 11
  • 23
Adam
  • 11
  • 3
  • What have you yourself tried to do to solve it? – Dexygen Dec 24 '19 at 12:27
  • I've tried adding return false; to the functions and also tried the preventDefault function to no avail. – Adam Dec 24 '19 at 12:50
  • I found this while researching, there's probably something useful in there: https://stackoverflow.com/questions/17642872/refresh-page-and-keep-scroll-position – Dexygen Dec 24 '19 at 13:57

1 Answers1

0

You probably just need to scroll the #trade-messages div to bottom after each update. See this answer for an easy fix.

Nathan Hawks
  • 557
  • 4
  • 14