JQuery and Rails
I am writing a Rails application and have to plug in this little jQuery code, but I really don't know how to make it work. Here's my controller code:
class ChatroomController < ApplicationController
def send_data
@role = Role.find_by_id(session[:role_id])
render :juggernaut do |page|
page.insert_html :bottom, 'chat_data', "<b>#{@role.name}:</b> #{h params[:chat_input]}<br>"
end
render :nothing => true
end
end
and the view code:
<h2>Chat</h2>
<html>
<head>
<%= javascript_include_tag :defaults, :juggernaut %>
<%= juggernaut %>
</head>
<body>
<div id='chat_data', class="chatbox">
</div>
<br>
<%= form_remote_tag(
:url => { :action => :send_data },
:complete => "$('chat_input').value = ''" ) %>
<%= text_area_tag( 'chat_input', '', { :rows => 3, :cols => 70, :id => 'chat_input'} ) %>
<%= submit_tag "Send" %>
</form>
</body>
</html>
Now I need the chat to always scroll to the bottom when any user sends a new message. But also when the current user is manually scrolling, disable this behavior. I found jQuery code here: Scrolling overflowing DIVs with JavaScript
Now I don't know how to make it work. I pasted in application.js:
$("#chat_data").each( function()
{
var scrollHeight = Math.max(this.scrollHeight, this.clientHeight);
this.scrollTop = scrollHeight - this.clientHeight;
});
I have also added <%= javascript_include_tag 'jquery', 'application' %>
to head
my submission.
But when my chat log fills up a scrollbar appears but doesn't automatically move to the bottom when new messages appear.
a source to share
The problem is that the code you entered is only run once, at the beginning of the script.
I don't know much about jquery, so this is just a general solution.
function sub(data) {
$('#chat_data').each( function () {
var s_top = this.scrollHeight - this.clientHeight;
var scl = this.scrollTop == s_top;
this.innerHTML += '<br/>' + data;
if ( scl ) this.scrollTop = s_top + this.clientHeight;
})
};
Problem is that now when you get new data from the server, you have to add it to #chat_data by calling sub ("the text that goes into the chat window").
you will need to replace
page.insert_html ....
with something that sends rjs to the client like:
page.call( :sub, data)
hope this helps.
a source to share