'How to open a random link stored in a json file from an image on a HTML page
I have a HTML webpage and it has an image on it. When the image is clicked I want it to open a random link which is (currently) stored within a list on a json file on the same server.
HTML
<a href="#"><img src="ZEL.png" width="75" height="75"/></a>
nodes.json
[
{
"title": "2030",
"url": "https://zero2030.net",
"feed": "https://zero2030.net"
},
{
"title": "2040",
"url": "https://zero2040.net",
"feed": "https://zero2040.net"
},
{
"title": "2050",
"url": "https://zero2050.net",
"feed": "https://zero2050.net"
}
]
If there is a better html/javascript/css/json method happy to take on board
Thank you
Solution 1:[1]
a simple way with map method for set random link from json
i have changed href attribute to test for testing
const links = [
{ title: "2030", url: "https://zero2030.net", feed: "https://zero2030.net" },
{ title: "2040", url: "https://zero2040.net", feed: "https://zero2040.net" },
{ title: "2050", url: "https://zero2050.net", feed: "https://zero2050.net" }
];
const link = document.querySelector("a");
let url = links.map((url) => url.url);
link.addEventListener("click", (e) => {
let randHref = url[Math.floor(Math.random() * links.length)];
e.currentTarget.setAttribute("test", randHref);
});
a:after{
content :'random href : 'attr(test);
display: block;
color: red;
padding: 5px;
}
img{
border : 5px solid;
}
<a test="default href" ><img src="ZEL.png" width="75" height="75"/></a>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ahmad MRF |
