DevOverflow
DevOverflow

Reputation: 39

Insert (random) javascript array item into href

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.

Upvotes: 0

Views: 336

Answers (2)

mwilson
mwilson

Reputation: 12960

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>

Upvotes: 1

Aalexander
Aalexander

Reputation: 5004

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>

Upvotes: 1

Related Questions