Forum Moderators: open

Message Too Old, No Replies

Random Link Within a DIV

I need a short script

         

cookiemonster

1:33 pm on Jan 23, 2010 (gmt 0)

10+ Year Member



Hello,

I want to make a random link button that takes a random link out of a div.
I found this javascript somewhere on the net:


<script>
function random_all(){
var myrandom=Math.round(Math.random()*(document.links.length-1))
window.location=document.links[myrandom].href
}
</script>

It takes all the links on the page and gets a random one out of those.
I need a script that does that, except only takes the links out of a specified div.

I tried:


<script>
function random_all(){
var myrandom=Math.round(Math.random()*(document.getElementById('test').links.length-1))
window.location=document.links[myrandom].href
}
</script>

but it didn't work.

Any ideas?
Thanks!

PS, I don't want to manually insert the links into an array because there's going to be thousands of links :P

PCInk

1:44 pm on Jan 23, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



In your second example, you are getting the number of links in the 'test' div and taking a random number and storing it in 'myrandom'. Let's say the 10th (for arguments sake).

Then the next line, window.location=.... you are setting the location to the 10th link (for arguments sake, again!) in the document and not the 10th in the 'test' div. You will need to out the getElementById in that line as well when referring to the links.

I haven't tested it and it assumes the above works (i.e. no errors) but sends you to the wrong link.