You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails:渲染新Partial时强制将窗口滚动位置置顶

Fixing Scroll Position Reset When Rendering Rails Partials

Hey there! I get why that scroll position issue is frustrating—when users submit a form and load a new partial, they expect to start at the top, not stuck in the middle of the page. Let’s break down why your current code isn’t working and how to fix it.

Why Your Current JS Doesn’t Work

The $(document).ready() function only fires once, when the entire page finishes loading for the first time. When you render a new partial dynamically after form submission, you’re updating just a portion of the DOM—not reloading the whole page—so that ready event never triggers again.

Solutions Based on Your Rails Setup

1. If You’re Using Rails UJS (with remote: true in forms)

If your forms use form_with remote: true (or the older form_for remote: true), you can listen for the ajax:success event that Rails UJS triggers after a successful AJAX request. This will run right after the new partial is rendered:

// Add this to your application.js or a relevant JS file
$(document).on('ajax:success', 'form', function() {
  $(window).scrollTop(0);
});

You can make this more specific by adding a class to your registration forms (like .registration-form) and updating the selector to '.registration-form' if you don’t want it to affect all forms on the site.

2. If You’re Using Turbo (Rails 7 Default)

Rails 7 uses Turbo by default for dynamic page updates. Turbo emits a turbo:render event whenever it renders new content (like your partial). Listen for this event to reset the scroll position:

// Add this to your application.js or a dedicated JS file
document.addEventListener('turbo:render', function() {
  window.scrollTo(0, 0);
});

This will trigger every time Turbo updates the page content, which fits perfectly with your partial-switching registration flow.

3. Quick Fallback: Embed Script in Partials

If you need a simpler (though less clean) approach, you can add a small script tag at the bottom of each registration partial. This script will run as soon as the partial is inserted into the DOM:

<!-- Add this at the end of each partial in app/views/registrations/partials/ -->
<script>
  $(window).scrollTop(0);
</script>

Note that this adds duplicate code to each partial, so it’s better to use the event listener methods above if possible.

Which One Should You Choose?

  • Go with the Turbo event if you’re on Rails 7+ (most modern Rails apps).
  • Use the UJS ajax:success event if you’re using an older Rails version with UJS.
  • The embedded script is a quick fallback if neither of the above fits your setup.

Give one of these a try—your users will appreciate starting at the top of each new registration step!

内容的提问来源于stack exchange,提问作者wrahim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:53:32