I'm in the process of coding a random joke generator, and I was wondering how I could randomize the destination of an tag. I have good JavaScript skills, but as a 12 year old, I'm new to HTML and CSS. I don't know if it matters, but I code on Replit.
My idea is that I have three buttons, each determining the type of joke to generate, and then each has an tag that leads to a separate file with a joke. Currently, I have this
But of course, it only leads to one file, which means one joke, which means sad. I'm thinking that Javascript would be able to fix this, and I could maybe use a tag to import it or something. If you can help, then thank you!
CodePudding user response:
The key is to break it down:
- Define your list of possible destinations
- Select one at random
- Grab the DOM element to change
- Set the DOM element's href link to your random page
Here's a working example:
const destinations = [
'my-destination-1.html',
'my-destination-2.html',
'my-destination-3.html',
'my-destination-4.html',
'my-destination-5.html'
];
const randomIndex = Math.floor(Math.random()*destinations.length);
const randomDestination = destinations[randomIndex];
const randomJokeLink = document.getElementById('random-joke-link');
randomJokeLink.setAttribute("href", randomDestination);
<a id="random-joke-link" href="#">Random Joke</a>