Blogger Random Posts Button
It's good to keep the readers engaged in your content, so here is a button script to direct readers to a random post from your previous 50 posts. No need to cite me, though it would be nice. I release this code to the Public Domain.
All you have to install it is:
1. Copy the following code.
2. Go to your page or post you want to implement the button with. Change the view from "Compose view" to "HTML view".
3. Paste the code at the top or the bottom of the page.
4. Edit the code. Change the "BLOGNAME" to the URL of your blog.
<button onclick="randomPost()">Random Post</button>
<script>
async function randomPost() {
let blogUrl = "https://BLOGNAME.blogspot.com"; // Replace with your blog URL
let feedUrl = blogUrl + "/feeds/posts/default?alt=json&max-results=50"; // Fetches up to 50 posts
try {
let response = await fetch(feedUrl);
let data = await response.json();
let posts = data.feed.entry;
if (posts && posts.length > 0) {
let randomIndex = Math.floor(Math.random() * posts.length);
let randomPostUrl = posts[randomIndex].link.find(link => link.rel === "alternate").href;
window.location.href = randomPostUrl;
} else {
alert("No posts found!");
}
} catch (error) {
console.error("Error fetching posts:", error);
alert("Could not load posts.");
}
}
</script>
<script>
async function randomPost() {
let blogUrl = "https://BLOGNAME.blogspot.com"; // Replace with your blog URL
let feedUrl = blogUrl + "/feeds/posts/default?alt=json&max-results=50"; // Fetches up to 50 posts
try {
let response = await fetch(feedUrl);
let data = await response.json();
let posts = data.feed.entry;
if (posts && posts.length > 0) {
let randomIndex = Math.floor(Math.random() * posts.length);
let randomPostUrl = posts[randomIndex].link.find(link => link.rel === "alternate").href;
window.location.href = randomPostUrl;
} else {
alert("No posts found!");
}
} catch (error) {
console.error("Error fetching posts:", error);
alert("Could not load posts.");
}
}
</script>
Comments
Post a Comment