Skip to content

Commit d14ef58

Browse files
committed
refactor random post button to use anchor tag and set href dynamically
1 parent 734d5f9 commit d14ef58

3 files changed

Lines changed: 29 additions & 10 deletions

File tree

assets/common.css

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -961,6 +961,7 @@ code {
961961

962962
&:hover,
963963
&:focus {
964+
text-decoration: none;
964965
background: var(--color-accent-dark);
965966
color: var(--color-accent);
966967
border-color: var(--color-accent);

assets/randomblog.js

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,26 @@
1-
function redirectToRandomBlog() {
2-
const links = document.querySelectorAll("a.post-link[href]");
3-
if (!links.length) {
4-
document.body.innerText = "No blog posts found.";
5-
return;
1+
/**
2+
* A function to find all post links on the page and set the 'href'
3+
* of our "random post" link.
4+
*/
5+
function setRandomPostLink() {
6+
const randomPostLink = document.getElementById("random-post-link");
7+
8+
const postLinks = document.querySelectorAll("a.post-link[href]");
9+
10+
if (!randomPostLink || !postLinks.length) {
11+
if (randomPostLink) {
12+
randomPostLink.style.display = "none";
613
}
7-
const random = links[Math.floor(Math.random() * links.length)];
8-
window.location.href = random.getAttribute("href");
14+
return;
15+
}
16+
17+
const randomPost = postLinks[Math.floor(Math.random() * postLinks.length)];
18+
19+
randomPostLink.href = randomPost.getAttribute("href");
920
}
21+
document.addEventListener("DOMContentLoaded", setRandomPostLink);
22+
window.addEventListener("pageshow", function (event) {
23+
if (event.persisted) {
24+
setRandomPostLink();
25+
}
26+
});

layouts/blog/list.html

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,14 @@ <h1 class="animated">Blog ({{ len (where .Pages "Params.unlisted" "ne" true) }})
99
</div>
1010

1111
<div class="random-blog-btn-container animated">
12-
<button
13-
onclick="redirectToRandomBlog()"
12+
<a
13+
href="#"
14+
id="random-post-link"
1415
class="random-blog-btn"
1516
title="Go to a random blog post"
1617
>
1718
🎲 Random Post
18-
</button>
19+
</a>
1920
</div>
2021

2122
{{ partial "post-links.html" .Pages }}

0 commit comments

Comments
 (0)