   toggleChallengeEvent: (e) =>
     $popup = @$closestPopup(e.currentTarget)
     $challenge = $popup.find('.challenge')
-    wasAtBottom = @isAtBottom()
+    wasAtBottom = @isAtBottom($popup)
     if $challenge.hasClass("hidden")
       @createChallenge($popup)
     else if $challenge.find('.cancel_challenge').text() == 'Cancel'
       $popup.find('.send_challenge').click()
     else
       @closeChallenge(@messageFromPopup($popup))
-    if wasAtBottom then @scrollToBottom()
+    if wasAtBottom then @scrollToBottom($popup)
 
   sendChallengeEvent: (e) =>
     $popup = @$closestPopup(e.currentTarget)

        $popup.addClass('new_message')
        PokeBattle.notifyUser(PokeBattle.NotificationTypes.PRIVATE_MESSAGE, username)
      $messages.append("<p><strong>#{username}:</strong> #{message}</p>")
    if wasAtBottom then @scrollToBottom()

  openChallenge: (messageId, generation, conditions) =>
    $popup = @$findOrCreatePopup(messageId)


  # Returns true if the chat is scrolled to the bottom of the screen.
  # This also returns true if the messages are hidden.
  isAtBottom: ($popup) =>
    $el = $popup.find('.popup_messages')
    ($el[0].scrollHeight - $el.scrollTop() <= $el.outerHeight())

  scrollToBottom: ($popup) =>
    messages = $popup.find('.popup_messages')[0]
    messages.scrollTop = messages.scrollHeight
    false

