Return to the Same Browser Scroll Location After Form Submission to Mimic AJAX

I was working on a web app that allowed users to submit comments anywhere in a long feed of events. After submitting a comment, the page would refresh, bringing you back to the top. I found that to be annoying because I had to scroll back down to my comment to make sure it had been accepted.

Of course, I could have created AJAX commenting, but that would have taken more code and I was feeling lazy.

So, I tried this trick, which was to store the browser scroll position in a hidden form field, then scroll back to that point after the page reloads.

I found that this worked AMAZINGLY well! It was hard to even tell the page had refreshed! It looked like an AJAX form submission in fact! I had discovered “lazy man’s AJAX”! Here’s how to do it.

Adding a Hidden Field To Your Form

First, you’ll need to add a hidden input field to your form. This is where you’ll be storing the browser scroll position to send to the refreshed page. Here’s an example:

<input type="hidden" name="scrollPosition" class="scrollPosition" />

The JavaScript

Next, you’ll need some JavaScript.

The first part gets the browser scroll position and stores it in the form at submission

// STORE THE EXACT SCROLL AMOUNT WHEN FORM IS SUBMITTED.
    jQuery( ".journal-entry-form").submit( function() {
        jQuery(this).find( ".scrollPosition" ).val( window.scrollY );
    });

The next part of the code reads the scroll position (if it exists), and scrolls to that point.

<?php if ( isset($_POST["scrollPosition"] ) ): ?>
        // JUMP BACK TO SCROLL LOCATION WHEN FORM WAS SUBMITTED
        window.scrollTo( 0, <?php echo intval( $_POST["scrollPosition"] ); ?> );
    <?php endif; ?>

Like I said, I found this to work amazingly well! It really mimicked AJAX in look and feel in my application!

Conclusion

Did it work for you? Questions? Please leave a comment below. – Brian

Please Leave a Question or Comment

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Inline Feedbacks
View all comments
Kagiso
Kagiso
1 month ago

Hey. Thank you for sharing! Could you possibly share more of the full code? I’m having a hard time figuring out what goes where..

Shares
%d bloggers like this: