💾 Archived View for gemlog.blue › users › verachell › 1644777931.gmi captured on 2022-04-28 at 19:30:11. Gemini links have been rewritten to link to archived content

View Raw

More Information

⬅️ Previous capture (2022-03-01)

-=-=-=-=-=-=-

Button to reload the page and go to a section with a hash mark

Note: This post is a Gemini space version of my post originally published on June 1, 2020

https version of this post

While there are lots of ways to code it so a button reloads the page, it was hard to figure out how to do it in such a way that it goes automatically to a URL with a hash. So here is my solution that works, finally.

Update - better solution

Here is a better solution, since the one below worked for me on any page except the domain root. It may be the way my CMS is set up or it may be the way my server is set up, or most likely I'm missing something fundamental about the way the function works. Anyway, the better solution I've gone with doesn't include the hash in the URL, but it reloads to the point the user was last browsing at, which for my purposes worked out the same as the hash. So here is the solution I'm going with for now.

<button onClick="window.location.reload();">Generate New</button>

The solution I put earlier (see below) did not work for me in all instances, but it's worth trying out.

The initial problem

I needed a button that users could press to reload the page, but to go to the part of it with a hash.

This needed to occur even if the user started on the non-hash version of the page (e.g. at the top of the page). In that situation the user sees the button halfway down, presses it, and that causes page reloads to a point designated by a hash version of that same page. Many plain old reload commands would either reload the whole page but not redirect to the hash version, or, if I explicitly specified the hash version, it would go to that part of the page but without a reload.

The solution

Finally, I figured it out:

<button> onClick="window.location.href=window.location.href='https://yourdomain.com/yourpage#yoursection';">Refresh Page</button>

The above is literally all you need.

Optional extra info if you wish to specify page name as a variable

You probably plan to specify the page name programmatically. In the case of ProcessWire, and indeed many CMS's, in getting the page URL you will want to remove a trailing slash if there is one.

Here is the PHP code I'm using for ProcessWire, therefore it uses the PW API; adapt as needed for other CMS's. I'm putting it here mainly to have it handy for me whenever I need it again.

$thehrefhash = rtrim($page->httpUrl,'/').'#yoursection';

The simply replace the href string given in the solution with $thehrefhash