0

I have the following code. I would like to make it so that it delivers a href depending on the random array item served (which are the latter parts of the URL). In other words, it should randomly take you to either the Blog (http://website.com/blog), About page or Home page. I have taken note of the method used here: Getting a random value from a JavaScript array, but they only console log the output. I cannot find any examples of how I would then put that output into the latter part of the href.

<a id='link' href='http://website.com/'>Click me</a>

<script>
var pages = ['blog','about','home'];
</script>

I expect any answer will use the javascript math.random() function but I have left it out of my question to prevent making it more messy than necessary if I do not use it the most efficiently.

1
  • 1
    What have you tried to figure out how to add the randomly selected entry to the URL? Commented Feb 5, 2021 at 18:49

2 Answers 2

1

The idea is to get the random index of your array. Once you have the index, you can then grab the value from your array and set the href attribute.

const anchor = document.getElementById('link');
const pages = ['blog','about','home'];
const random = Math.floor(Math.random() * pages.length);
anchor.href = `http://website.com/${pages[random]}`;

// For Display Purposes Only
document.getElementById('display').innerText = anchor.href;
<a id='link' href='http://website.com/'>Click me</a>
<div id="display"></div>

Sign up to request clarification or add additional context in comments.

Comments

1

You can use the random element and then reassign the href property of the a tag.

var pages = ['blog','about','home'];
const randomElement = pages[Math.floor(Math.random() * pages.length)];

document.querySelector('a').href = `http://${randomElement}.com/`
console.log(document.querySelector('a').href )
<a id='link' href='http://website.com/'>Click me</a>

2 Comments

This answer also works perfectly, unfortunately can only pick one.
So you want use 2?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.