Home > Net >  I'm trying to create a button that links to a random page
I'm trying to create a button that links to a random page

Time:12-02

I'm new to coding and I'm trying to create a button that links to a random page in my simple website. I'm having issues modifying the "href" and making it go to the page on the click.

Here is the JavaScript I have written:

document.addEventListener("DOMContentLoaded", function(){
let arrayofpages = ["my_cat.html","about_me","art.html","index.html"]
let randompage = arrayofpages[Math.floor(Math.random()*arrayofpages.length)];

document.addEventListener("click",function(){
document.getElementById("lucky_btn").href = "${randompage}";
document.getElementById("lucky_btn").innerHTML = "random page";
});

I would appreciate any help I can get!

CodePudding user response:

The string "${randompage}" is literally just a string that says "${randompage}". Instead, use backticks:

`${randompage}`  // This creates a string out of the variable randompage

But in your case, since you're not doing anything with the string, the simplest way is to use the variable directly:

document.getElementById("lucky_btn").href = randompage;

In general, template literals are more useful for inserting variables into a longer string, like

let name = 'Sarah';
let quality = 'great';
let message = `Hello ${name}, have a ${quality} day`;

CodePudding user response:

A little bug in your code. you used double quotes "" instead of backticks ``.

This line

document.getElementById("lucky_btn").href = "${randompage}";

should be

document.getElementById("lucky_btn").href = `${randompage}`;

CodePudding user response:

Thank you for all the answers looking at them I have found the bug that was causing the issue, of not redirecting to a random page:

instead of

document.getElementById("lucky_btn").href = "${randompage}";

where I should have used backticks, I changed the code to:

 document.location.href = `${randompage}`;

and this has solved the problem!

update this has now introduced a new bug where if I click on anything within the page it redirects me to a random page rather than clicking the specific button.

  • Related