How do I program a "Random button" on my Blogger site?

146 Views Asked by At

I want to add a button/link that redirects the user to a randomly chosen post on my Blogger site. I plan for the button to be one of the links in the page list at the top of my Blogger site and have it redirect the user to a random page with each click.

I've added an "HTML/JavaScript" gadget in the footer on my site and tried figuring things out from there. Unfortunately, nothing I've done has brought me success with this idea yet. I've tried having it so that when the site is loaded, the link gets a randomly chosen URL that redirects to a post on my website, however, it only picks the recent posts and not the older ones. I plan for this random link to randomly pick out of all of my posts, not just the newer ones.

Here is the code for the page list (the URLs I censored):

{
"link0":{"href":"http://###/","position":0,"title":"Home"},
"1442808221004497204":{"href":"https://###","position":1,"title":"About"},
"2724719100104741041":{"href":"https://###","position":2,"title":"Contact"},
"link1":{"href":"javascript:randomPost()","position":3,"title":"Random"}
}

And here is the code for the HTML/JavaScript gadget:

<script>
function randomPost() {
  // Get all post URLs on the page
  var postLinks = document.querySelectorAll('.post-title a');

  // Generate a random index
  var randomIndex = Math.floor(Math.random() * postLinks.length);

  // Get the URL of the randomly chosen post
  var randomPostUrl = postLinks[randomIndex].getAttribute('href');

  // Redirect to the random post
  window.location.href = randomPostUrl;
}
</script>
1

There are 1 best solutions below

0
Suramuthu R On
  1. In the following code in the line starting with const urls, replace all the dummy urls with your blog post urls. you can add as many urls as you want. Each urls should be placed within doublequotes and separated by comma.

  2. Go to the Layout in blogger. Select a blank widget where you actually want to place your button.

  3. Select add html/javascript widger

  4. Copy the following code(with corrected urls) in the widget. Save it and close.

  5. Also save it using the save button in the layout section as well.

Now you will get random posts loaded as you click the button.

In case if you want the post to be loaded in another tab, replace "_self" with "_blank" in the line starting with window.open

 <script>

 function randomPost(){

 const urls = ["http://###/", "http://###/", "http://###/", "http://###/", "http://###/",]

 let urlIdx = Math.floor(Math.random() * urls.length)

 let randomUrl =urls[urlIdx]

 window.open(randomUrl, "_self")

 
 }

  </script>

 <button onclick="randomPost()">Random Post</button>