Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maintain scroll position after submit

Tags:

javascript

I’m using this as basis for my website. Under the link Contact I put contact form with PHP validation to check if user has filled in the fields properly. After the submit button is clicked, either:

  1. the validation message (e.g. “Sorry, your name is a required field” etc) is displayed, or
  2. the message “Thank you for filling out the form” (if all the fields were filled properly ) is displayed.

However, the page then jumps back to the first page, showing the “About” page. If you navigate back to “Contact” page you can see the messages. This is very annoying.

Example of my attempts can be found here:

I'm a beginner in this field and any hint or tip where to look further would be much appreciated.

like image 766
user3764703 Avatar asked Nov 01 '22 21:11

user3764703


1 Answers

I would redirect to the original URL adding a hash to the URL that will tell your site where to go to.

When comment.php is being executed it would respond with a 302 redirect with #contact attached. Say your page is index.html it would redirect to

/index.html#contact

About redirect in PHP: http://php.net/manual/en/function.header.php

In index.html you'd then check for the hash and do what ever you do when clicking the link:

window.onload = function(){
   if (location.hash === "contact") {
      goto('#contact', this);
   }
}

If the pages are delived by the same page as the comment handler, e.g. index.php you could also post the form to index.php with #contact appended. You'll then need no redirect in PHP.

<form action="/index.php#contact" method="POST" ...>
  ...
</form>

1st benefit: you could build your page to work without Javascript too (useful for visitors using script blockers). The page containers would be block elements, one below the other. The #<name> will then automatically jump to the container that has an id="<name>" attribute. You need to add a CSS class to make the page containers side by side within the onload event.

2nd benefit: if you check the hash value for correct values and then pass it directly to your goto(), users will be able to bookmark the page and when revisiting your site will jump to the right "page".

like image 118
try-catch-finally Avatar answered Nov 08 '22 10:11

try-catch-finally