I am working on a Rails application and have a form that, upon submission, it to increase the window.history.length. I want the “Back” button to take the user back through all the history entries when clicked.
Here’s the structure of my code:
app/views/media/_form.html.slim
$( ".form" ).submit(function(event) {
$('.form').addClass('loading');
});
In the dashboard layout, I have a back button to allow users to navigate back through the history. Here’s the JavaScript for that:
_app/views/share/v2/menu.html.slim
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('.back-button').addEventListener('click', (event) => {
event.preventDefault();
window.history.back();
});
});
Problem:
Each time the user edits the form, window.history.length increases by the number of times they submit the form (e.g., 2 or 3 times). As a result, the user has to click the back button 2 or 3 times to go back to the previous page.
Expected Behavior:
When the user clicks the “Back” button, I want them to be taken directly to the previous page with one click, regardless of how many times the form was edited or submitted.
I have tried this
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('.back-button').addEventListener('click', (event) => {
event.preventDefault();
var goback = window.history.length;
window.history.go(-goback);
});
back button not working, also tried
$( ".form" ).submit(function(event) {
$('.form').addClass('loading');
setTimeout(function() {
window.history.go(0);
}, 2000);
});
I have multiple forms in my Rails application (media, product, giveaway, league, etc.). I’m trying to use window.history.go(0) to reload the page after form submission without adding a timeout, but it only works when I add a setTimeout.
Problem: I don’t want to use a timeout for multiple forms. Without the timeout, window.history.go(0) doesn’t trigger. Is there a way to make it work without a delay? or any other solution to play around.
Thank you!!