0

I built a chat using actioncable and I'm using this coffeescript.

I basically want it to automatically scroll down whenever there's a new message (or div) in the chatbox.

personal_chat.coffee

jQuery ->
  if $('#current-user').size() > 0
    App.personal_chat = App.cable.subscriptions.create {
      channel: "NotificationsChannel"
      user_id: $('#current-user').data('id')
    },
    connected: ->
  # Called when the subscription is ready for use on the server

    disconnected: ->
      # Called when the subscription has been terminated by the server

    received: (data) ->
      conversation = $('#conversation-body')
      if conversation.size() > 0 && conversation.data('conversation-id') is data['conversation_id']
        conversation.append data['message']
        user_id = $('meta[name=user-id]').attr('content')
        div = $('#conversation-body div:last')
        div.removeClass('to from')
        # from to append START
        if user_id == div.data('receiver').toString()
          div.addClass('from')
          $('#play-sound').get(0).play()
        else
          div.addClass('to')
        #from to append END
      else
        $.getScript('/conversations') if $('#conversations').size() > 0
        $('body').append(data['notification']) if data['notification']

    send_message: (message, conversation_id) ->
      @perform 'send_message', message: message, conversation_id: conversation_id

  $(document).on 'click', '#notification .close', ->
    $(this).parents('#notification').fadeOut(1000)

  $('.async-conversation').submit (e) ->
    $this = $(this)
    textarea = $this.find('#personal_message_body')
    if $.trim(textarea.val()).length > 0
      App.personal_chat.send_message textarea.val(), $this.find('#conversation_id').val()
      textarea.val('')
    e.preventDefault()
    return false

EDIT: I've tried the answer that was considered a duplicate, but it's not working. I'm not sure where to put that code in my coffeescript since i'm not familiar with this language.

Raidspec
  • 652
  • 1
  • 6
  • 13
  • 1
    Duplicate: http://stackoverflow.com/questions/270612/scroll-to-bottom-of-div – Tyler Biscoe Feb 01 '17 at 20:10
  • Possible duplicate of [Scroll to bottom of div?](http://stackoverflow.com/questions/270612/scroll-to-bottom-of-div) – schu34 Feb 01 '17 at 20:16
  • I was able to find a way to get the chatbox to scroll to the bottom on each submit, but it won't scroll to the bottom when each new div (or message in this case) comes in. Something like that, I think, should be done on personal_chat.coffee page. i've tried '$("#mydiv").scrollTop($("#mydiv")[0].scrollHeight); ' But not working out well – Raidspec Feb 01 '17 at 22:52
  • @schu34 no, not duplicate exactly – Raidspec Feb 03 '17 at 01:08

0 Answers0