Screeching Kitten Soul Screeching Kitten Soul - 1 month ago 7
HTML Question

random html link selector from group of links

random html link selector from group of links.

so i have this image on my site, when clicked it takes you to a html page. that's good, only thing is i want it to randomly select a link from a group of lets say five links, not just 1 html link.

<a href="url" target="_blank"><img id="img-hover" src="image"/></a>


i need the function of the code above still to work. so please incorporate your code with mine. sorry for english. also, this code goes off of some java but i don't think you need it. but here it is.

<script type="text/javascript">

var timer;

document.getElementById('img-hover').addEventListener('mouseover', function() {
clearTimeout(timer);
var elem = this;
timer = setTimeout(function() {
elem.src='image';
}, 9000);
});

document.getElementById('img-hover').addEventListener('mouseout', function() {
clearTimeout(timer);
var elem = this;
timer = setTimeout(function() {
elem.src='image?v=513d43d2';
}, 9999999999999999);
});
</script>

Answer

Try something like this, but replace the URL's with your own, of course.

<a href="#" onclick="randomUrl();" target="_blank"><img id="img-hover" src="image"/></a>
var urlArray = [
    "http://www.google.com",
    "http://www.yahoo.com",
    "http://www.stackoverflow.com"
];

function randomUrl() {
    var randomNumber = Math.floor(Math.random() * urlArray.length);
    var newUrl = urlArray[randomNumber];
    window.location.href = newUrl;
}

JSFiddle