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

I am a freelance web developer and consultant based in Santa Monica, CA. I’ve been designing websites using WordPress and from scratch using HTML, CSS, PHP, and JavaScript since 2010. I create websites and web applications for businesses, nonprofits, and other organizations. I have a degree in Electrical Engineering (BSEE) from California Institute of Technology and a degree in Engineering Management (MSEM) from Stanford University.
Discover more from Web Developer Tips and Tricks
Subscribe to get the latest posts sent to your email.
Please Leave a Question or Comment
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..
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