Chrome automatically scrolling back to the beginning of the page following a remote form submission

Rails Version: 5.2.2

Chrome Version: 78.0.3904.87

While testing my website on Chrome today, I encountered an issue where the page automatically scrolls to the top whenever an AJAX request is made. This problem only occurs in Chrome and not in other browsers like Firefox. Despite trying to debug the root cause of this behavior, I have been unsuccessful in finding a solution.

Below is the structure of the form triggering the AJAX request:

<div id="container">
  <%= form_for(obj, method: :post, url: url, remote: true) do |f| %>
    <button id="obj-<%= obj.id %>-btn" type="button" class="btn btn-primary obj-btn" title="Add" data-toggle="tooltip" data-placement="left">
      Add
    </button>
  <% end %>
</div>

Here is the JavaScript code responsible for submitting the form:

$("#container").on("click", "form > .obj-btn", function(e)
{
  $(this).tooltip('hide');

  var form = $(this).parent();

  form.submit();
});

Upon sending the request to the server, the controller executes JavaScript contained in a create.js.erb file.

I have explored various suggestions from different sources, such as adding e.preventDefault() or return false; in the submit handler, but these methods did not resolve the issue for me.

If anyone has any insights or solutions to this problem, your assistance would be greatly appreciated. Thank you.

Answer №1

Instead of capturing the button click event, it's better to listen for and handle the submit event on your form. By using e.preventDefault() in this case, you can prevent the default submission behavior that causes your page to refresh. Your code should look something like this:

$(document).ready(function () {
  // ***** Listen for the submit event on the form ***** //
  $('#form').submit(function (e) {

    e.preventDefault();

    // Gather data from the form 
    // and submit it manually via AJAX

  });
});

Answer №2

When utilizing e.preventDefault(), the page will not refresh following a successful AJAX request. To remedy this, you can manually reload the page using window.location.reload() in your JavaScript code.

Answer №3

When you submit a form, it's not an ajax request, so the browser typically goes to the top of the page. It's like navigating to another page.

There are two options available, as suggested by some other answers:

  1. Use a real ajax request (like $.ajax, a native method, or methods provided by your client-side framework).
  2. Add JavaScript to the page to automatically scroll to the section you want.

I believe the first option is what you're after since the second one could cause the page to jump up and down.

Answer №4

Typically, when a button within a form is clicked, it triggers the submission of the form and reloads the page.

Alternatively, you could convert the button to an <a> tag to prevent the automatic form submission. However, keep in mind that you would need to handle the form submission manually. I hope this suggestion proves helpful.

Answer №5

After struggling with this particular problem for quite some time, I finally figured out that the root cause lies within the font_awesome5_rails gem that is part of my project setup. This issue persisted even when I attempted to handle it through AJAX requests.

To resolve the problem, I decided to switch to utilizing Font Awesome as an SVG through JavaScript. Surprisingly, removing the icons from the layout prevented Chrome from continuously jumping to the top of the page. Moving forward, I plan on raising this issue with the appropriate channels and conducting further investigation into the matter.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Looking for someone who has successfully upgraded React Native code from version 0.59 to the most recent version

Is there a way to make my React Native project compatible with the latest version? I am facing a challenge in updating an old React Native project running on version 0.59.10 to the most recent version. Despite trying various methods, I have been unable to ...

Retrieving Form Validation Error Value in AngularJS

Incorporating AngularJS 1.2 RC2 and utilizing Bootstrap for CSS, I have constructed a straightforward form as shown below: <form class="form-horizontal" name="form" novalidate> <label class="col-lg-2 control-label" for="name">Name</labe ...

Challenges Encountered when Making Multiple API Requests

I've encountered a puzzling issue with an ngrx effect I developed to fetch data from multiple API calls. Strangely, while some calls return data successfully, others are returning null for no apparent reason. Effect: @Effect() loadMoveList$: Obse ...

Using AJAX to fetch data for Highcharts illustration

Hello there! I am attempting to create a chart based on data retrieved via AJAX. The values for the chart are coming from the AJAX return. Here is the data that I have: "tgl":["2016-07-12 00:00:00.000","2016-07-01 00:00:00.000"],"total":[1283947,12346185 ...

Tips for preventing a table from showing up while scrolling unnecessarily when utilizing a heading with the CSS position property set to 'sticky'

Currently, I am facing an issue with creating a sticky header for my table. The problem arises when the header of the table has rounded edges (top right and top left) along with a box-shadow applied to the entire table. As the user scrolls through the tabl ...

What are the steps to crafting a personalized message for the valid() method in the JOI library?

To validate the property subscription, I use the following method: Joi.object({ subscription: Joi.string() .valid('starter', 'pro', 'business') .required() .messages({ 'string.base': `{{#label}} s ...

The next function is not defined error in the controller function

Everything was running smoothly until I suddenly encountered this error message: ReferenceError: next is not defined. I'm puzzled because I didn't make any changes to this function. const Users = require('../data/users.model') exports ...

How can the dependencies object be extracted from the package.json file in an Angular project?

Scenario: I am managing multiple Angular applications within the same project. Whenever I need to upgrade an npm package, I find myself having to manually update the package.json files in each application. While I attempted a mono repo approach, it did not ...

Glitch in transmitting server data to client in MERN stack development

I am currently developing a MERN web application and I've encountered a bug in which the data retrieved from the server is not matching what is expected when making a GET request on the client side. Below is the controller function on the server for ...

The outcome of the Javascript Calculator is showing as "Undefined"

I've been attempting to create a calculator using JavaScript, but I'm facing an issue where the 'operate' function keeps returning Undefined, and I can't seem to figure out why. I suspect that the problem lies with the switch state ...

What is the most effective way to eliminate asynchronicity in a function?

Imagine having this block of code: const myFunction = async => { const result = await foobar() } const foobar = async () => { const result = {} result.foo = await foo() result.bar = await bar() return result } Now, let's transform i ...

Incorporate a Variety of Elements onto Your Webpage

I have developed a custom tooltip plugin using JQuery, and I am implementing it on multiple A tags. Each A tag should have a unique tooltip associated with it, so I have the following code: var $tooltip = $("<div>").attr("id", tooltip.id).attr("cla ...

Begin Leaflet with JQuery UI Slider set to a predefined value

I have integrated the LeafletSlider library into my project to slide through multiple layers with different timestamps in Leaflet. My goal is to initialize the slider at the timestamp closest to the current time. In SliderControl.js, I made the following ...

Encountering an error code of 500 when executing the createIndex function in Pouch

I'm currently working on setting up a basic index, and I have the following code snippet: currentDB.createIndex({ index: { fields: ['name'] } }).then((result) => { }).catch((error) => { }) However, when I try to r ...

Tips for managing the velocity of JavaScript navigation scrolling

Hey everyone, I recently discovered this incredibly helpful JavaScript sticky side navigation script and it works like a charm! However, since I don't know much about JS, I was wondering if there's a way to slow down the scrolling speed? functio ...

The 'slice' method is not accessible with the Kendo Grid Object

Attempting to connect the kendo grid to a WCF remote odata service is proving challenging. The grid fails to populate, throwing an exception Object doesn't support property or method 'slice'. Here's the javascript code used to initializ ...

React - group several elements within a wrapping container

I am dealing with an array of words that make up sentences: let words = [ { "start_time": "2.54", "end_time": "3.28", "alternatives": [ { "confidence": "1.0", ...

The error message "Cannot call expressjs listen on socket.ip" indicates that there

Currently working on a project involving websockets, but encountering an error in the code below: TypeError: require(...).listen is not a function Here's what I have tried so far: const app = require("express")(); const port = 3800; const ...

Tips for halting the movement of marquee text once it reaches the center briefly before resuming animation

Is there a way to make text slide in, pause when centered, and then repeat the process? I'm looking for some help with this animation. Here is the code snippet: <marquee direction="left" id="artistslide"> <span id="currentartist">< ...

Clicking on a flex card will trigger the opening of a new page where the parsed data will be displayed in a stylish manner using JavaScript

Currently, I am attempting to showcase the data retrieved from the following URL: . My objective is to format the parsed data with a specific style. However, I have encountered difficulties accomplishing this using `window.open()`. Any assistance in resolv ...