I want random links in this code to open in a new window. how to please ?

<script language="JavaScript">
<!--
// Create arrays to contain all the values 
// for links and image locations
link = new Array
image = new Array

link[1]="http://www.wildexpo.com.au/Aust%20Rep%20Show/"
image[1]="http://www.reptilesaustralia.com.au/forums/Ads/wildexpo.gif"

link[2]="http://www.excite.com"
image[2]="http://www.excite.com/mesp/images/excite/new_logo-180.gif"

link[3]="http://www.lycos.com"
image[3]="http://a284.g.akamai.net/7/284/987/000/lygo.com/ly/i/lyguide.gif"

link[4]="http://www.cnet.com"
image[4]="http://cnet.com/Images/Headers/cnet-1-title.gif"

link[5]="http://www.webcrawler.com"
image[5]="http://webcrawler.com/img/web/hdr/home_header.gif"


// Create a random number between 1 and five
random_num = (Math.round((Math.random()*4)+1))


// Write a link and images with random array
document.write("<a href=\"" + link[random_num] + "\">");
document.write("<img src=\"" + image[random_num] + "\" border=\"0\"></a>");

-->
</script>

Recommended Answers

All 5 Replies

target = "_blank" should work.

change:

document.write("<a href=\"" + link[random_num] + "\">");

to

document.write("<a href=\"" + link[random_num] + "\" target=\"_blank\">");

Thanks Again Matt! :D

Resolved!

Not Quite Resolved! :( Whats wrong with back slash? The code works in testbed but wont cop the backslash on my board (ipb) ?

document.write("<a href=\"" + link[random_num] + "\" target=\"_blank\">");

document.write("<img src=\"" + image[random_num] + "\" border=\"0\"></a>");

Not Quite Resolved! :( Whats wrong with back slash? The code works in testbed but wont cop the backslash on my board (ipb) ?

Hmm... perhaps your board software is looking for escaped characters and eating them.. o_O

try either:

document.write("<a href=\\"" + link[random_num] + "\\" target=\\"_blank\\">");
document.write("<img src=\\"" + image[random_num] + "\\" border=\\"0\\"></a>");

(double backslash should be escaped to backslash by your board software which can then go on to be the javascript escape character when the page is rendered)

or (my prefered way):

document.write('<a href="' + link[random_num] + '" target="_blank">');
document.write('<img src="' + image[random_num] + '" border="0"></a>');

(all literal strings in the Javascript are quoted with single quote characters, and attributes in the dynamically created elements are quoted with double quote characters :- escaping doesn't matter)

Matt to the resue! :D Once again Thankyou mate!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.