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

Shares

4 thoughts on “Return to the Same Browser Scroll Location After Form Submission to Mimic AJAX”

  1. 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..

    Reply
    • Hi Kagiso,

      Ah, sorry, this code is not really beginner-friendly. You have to be able to add PHP, HTML, and JavaScript to your app. You might need to get a developer to help.

      Best,
      Brian

      Reply

Leave a Reply to Kagiso Cancel reply