I'm new to html, and I also have no idea how to work with js, so can I insert a link in multiple images inside of javascript of an html?
Here is a code that make the image change every time I refresh,
What I need to do is make these image clickable, and leading to another site
Preferably, I'd want to try to make it so that the js can lead to a code in html, so i can also add stuff such as height
<a href="3.html"> <img src="3w.png" alt="car" height="333"> </a>
function random_imglink() {
var myimages = new Array()
myimages[1] = "1.png"
myimages[2] = "2.png"
myimages[3] = "3w.png"
myimages[4] = "4w.png"
var ry = Math.floor(Math.random() * myimages.length)
if (ry == 0)
ry = 1
document.write('<img src="' myimages[ry] '" border=0>')
}
random_imglink()
CodePudding user response:
- Arrays are 0 based so no need to force 1 when 0
- Just change the HTML to be a link
- It is recommended to not use document.write, so instead insert it into a container
I am using template literals to create the link and eventListener to see when the page has loaded
const myimages = ["1.png", "2.png", "3w.png", "4w.png"]
const links = ["page1.html","page2.html","page3.html","page4.html"];
function random_imglink() {
var ry = Math.floor(Math.random() * myimages.length)
return `<a href="${links[ry]}"><img src="${myimages[ry]}" height="333" border=0/></a>`;
}
window.addEventListener("DOMContentLoaded", function() {
document.getElementById("linkContainer").innerHTML = random_imglink();
});
<div id="linkContainer"></div>