diff options
Diffstat (limited to 'app/javascript')
-rw-r--r-- | app/javascript/channels/chat_room_channel.js | 11 | ||||
-rw-r--r-- | app/javascript/controllers/results_controller.js | 13 |
2 files changed, 21 insertions, 3 deletions
diff --git a/app/javascript/channels/chat_room_channel.js b/app/javascript/channels/chat_room_channel.js index af29953..514742f 100644 --- a/app/javascript/channels/chat_room_channel.js +++ b/app/javascript/channels/chat_room_channel.js @@ -10,14 +10,19 @@ consumer.subscriptions.create("ChatRoomChannel", { }, received(data) { + // If scrolled to the bottom or near the bottom, then smooth scroll to the bottom. + var shouldScroll = false; + var chatOutputElement = document.getElementById("chat_output"); + if ((chatOutputElement.scrollTop + 100) >= (chatOutputElement.scrollHeight - chatOutputElement.offsetHeight)) { + shouldScroll = true; + } + // Called when there's incoming data on the websocket for this channel var node = document.createElement("P"); node.innerHTML = data.html; - var chatOutputElement = document.getElementById("chat_output"); chatOutputElement.appendChild(node); - // If scrolled to the bottom or near the bottom, then smooth scroll to the bottom. - if ((chatOutputElement.scrollTop + 100) >= (chatOutputElement.scrollHeight - chatOutputElement.offsetHeight)) { + if (shouldScroll) { chatOutputElement.scrollTo({ top: chatOutputElement.scrollHeight, left: 0, behavior: 'smooth' }); diff --git a/app/javascript/controllers/results_controller.js b/app/javascript/controllers/results_controller.js new file mode 100644 index 0000000..266b80c --- /dev/null +++ b/app/javascript/controllers/results_controller.js @@ -0,0 +1,13 @@ +import { Controller } from "stimulus"; + +export default class extends Controller { + static targets = [ "output" ]; + + connect() { + this.scrollToBottom(); + } + + scrollToBottom() { + this.outputTarget.scrollTop = this.outputTarget.scrollHeight; + } +} |