<html>
<head>
<script>
// Declare an array with links as strings
var links = ["google.com", "youtube.com", "reddit.com", "apple.com"];
// Define a function to display a random link
function displayRandomLink() {
// Generate a random index within the range of the array
var randomIndex = Math.random() * links.length;
// Round down the random index to an integer
randomIndex = Math.floor(randomIndex);
// Get the element at the random index from the array
var randomLink = links[randomIndex];
// Get the HTML element to display the link
var linkElement = document.getElementById("random-link");
// Set the text and href attribute of the element to the random link
linkElement.textContent = randomLink;
linkElement.href = "http://" + randomLink;
}
</script>
</head>
<body>
<h1>Random Link Generator</h1>
<p>Click the button below to generate and display a random link.</p>
<button onclick="displayRandomLink()">Generate</button>
<p id="random-link"></p>
</body>
</html>
And you need to update your javascript function too
function displayRandomLink() {
var randomLink = links[randomIndex];
var linkElement = document.getElementById("random-link");
// Set the href attribute and text content
linkElement.href = "http://" + randomLink;
linkElement.textContent = randomLink;
}
With this the button will turn the text into a clickable hyperlink. The target="_blank" attribute in the <a> tag ensures that the link opens in a new tab.
It works really well now Thanks. Is there a way to change the display name I have a bunch of Google docs I need to be messing with in this and having a custom display name will be so much better than random nonsense huge link.
You’ll need to modify your JavaScript to display a custom name instead of the URL. It’s better if you define an array since it’s multiple links.
Something like this:
// You declare an array with objects containing links and their display names
var links = [
{ url: "google.com", name: "Google" },
{ url: "youtube.com", name: "YouTube" },
{ url: "replit.com", name: "Replit" },
{ url: "idontknow.com", name: "Idk" }
];
function displayRandomLink() {
var randomIndex = Math.floor(Math.random() * links.length);
var randomLink = links[randomIndex];
var linkElement = document.getElementById("random-link");
// Set the href attribute to the URL and text content to the custom name
linkElement.href = "http://" + randomLink.url;
linkElement.textContent = randomLink.name;
}