开发者

How to scroll to top from *.js.erb file

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 work开发者_StackOverflow中文版ed) 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.erb code inside another $(document).ready block. When the document is loaded and the ready event fires, each block of code passed to $(document).ready will be executed, in order.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜