I’m developing a website using Rails 3, and at this moment I wanted to scroll to top after showing an error message (which is displayed at the top of the page).
So far, I’ve tried the following, from my display_error_message.js.erb file:
$('#general-messages').html("<%= escape_javascript(render :partial => 'shared/error_message', :object => flash[:error]) %>");
$('html, body').animate({scrollTop:0}, 100);
This didn’t work. I mean, the first line worked fine, but not the second one.
After this try, I’ve tried to write the following code (just to see if it worked) in my view, and it worked, indeed:
$(document).ready(function () {
$('#to-top').click(function () {
$('html, body').animate({scrollTop:0}, 100);
});
});
Then, I realized that it was to do with document ready event, but I cannot use it (I think) from my js.erb file, or at least it doesn’t make sense to me.
Could you please tell me how to do this?
You are allowed to put your
.js.erbcode inside another$(document).readyblock. When the document is loaded and thereadyevent fires, each block of code passed to$(document).readywill be executed, in order.