0

I just created a basic web chat application, the problem is that each time a user sends a message the page scrolls up automatically. That the page doesn't refresh when I send the message so it shouldn't scroll up. Any idea how to solve this problem?

Partial _new_message.html.erb

<% if signed_in? %>
  <%= form_for([@room, @room.messages.build], remote: true) do |f| %>
  <div class="row">
    <div class="message-area col-xs-10 col-sm-10 col-md-11">
      <%= f.text_area :body, class: 'form-control', placeholder:'Type your message..', id:'exampleTextarea', rows:'2' %>
    </div>
    <span>
      <%= button_tag "", type: 'submit', class: "btn btn-default glyphicon glyphicon-send send-message col-xs-2 col-sm-2 col-md-1" %>
      <!-- <%= f.submit "Submit", class:'btn btn-primary send-message col-md-1' %> -->
    </span>
  </div>
  <% end %>
<% end %>

Partial _message.html.erb

<div class="message-append">
  <% @messages.each do |message| %>
  <div class="message-wrap"><%= message.user.user_name %>: <%= message.body %>
    <% if signed_in? && current_user.admin? %>
      <%= link_to ('<span class="glyphicon glyphicon-remove"></span>').html_safe, room_message_path(message.room, message), method: :delete, data: { confirm: 'Are you sure?' } %>
    <% end %>
  </div>
  <div class="message-divider"></div>
  <% end %>
</div>

Javascript

received: function(data) {
    // Called when there's incoming data on the websocket for this channel
    $('.message-append').append(data.message);
  },

  listen_to_messages: function() {
    return this.perform('listen', {
      room_id: $("[data-room-id]").data("room-id")
    });
  }
});

$(document).on('turbolinks:load', function() {
  App.room.listen_to_messages();
});
BoB
  • 133
  • 1
  • 11

2 Answers2

1

If you want it to stay at the bottom of the page you can use something like this:

window.scrollTo(0,document.body.scrollHeight);

You call it each time the message is appended

Deckerz
  • 2,606
  • 14
  • 33
1

This is a UI problem and you can solve it either in Javascript or coffeescript code.

Create a function which will identify your desired div.
"message-append" in this your case and use StrollTop like below:

  scroll_bottom: function() {
    $('.message-append').scrollTop($('.message-append')[0].scrollHeight)
  }

You need to update your receive method:

 received: function(data) {
    // Called when there's incoming data on the websocket for this channel
    $('.message-append').append(data.message);
    scroll_bottom();
  },

Similarly update your Turbolinks:loads

 $(document).on('turbolinks:load', function() {
  App.room.listen_to_messages();
  scroll_bottom();
});
ritzz.soni
  • 335
  • 1
  • 15