By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,310 Members | 1,430 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,310 IT Pros & Developers. It's quick & easy.

need script to choose random background-image

P: n/a
Hello comp.lang.js.I need a script to rotate a background image on
each newpage load, given the id of the element and a list (array?)of 2 or
more image paths ("img1.jpg", "img2.jpg", ...).Actually, depending on
how I write the HTML, I guess I'dneed the script to set
style.backgroundImage or src.I'd need to run it on a few elements, something
like:setRandomBgImg('thingy1', ('img1a','img1b', ...)
)setRandomBgImg('thingy2', ('img2a','img2b', ...) ) etcBut I don't actually know any more
javascript. :(Can you help? Thanks!! Lucy
Jul 23 '05 #1
Share this Question
Share on Google+
6 Replies


P: n/a
This Little script let you cicle between 2 images
<body>
<script language = "Javascript">

<!--

//nº of pictures

var npic=Math.round(Math.random())

//name of pictures

namepics= new Array("1.jpg","2.jpg");

document.write("<img src='" + namepics[npic] + "' >");

//-->

</script>
</body>

Unfortunatelly I haven´t figure out out to work with more than two images
tough
Jul 23 '05 #2

P: n/a
Again here is a solution that works perfectly for 5 (five)
images
<script language="Javascript">
<!--
npic=Math.random()
if (npic < 0.2)
document.write("<img src=1.jpg>");
else if (npic <0.4)
document.write("<img src=2.jpg>");
else if (npic <0.6)
document.write("<img src=3.jpg>");
else if (npic <0.8)
document.write("<img src=4.jpg>");
else
document.write("<img src=5.jpg>");

//-->
</script>

Jul 23 '05 #3

P: n/a
On Fri, 24 Sep 2004 17:15:13 +0100, Oscar Monteiro <of**@hotmail.com>
wrote:
This Little script let you cicle between 2 images
<body>
<script language = "Javascript">
The language attribute is deprecated in favour of the (required) type
attribute.

<script type="text/javascript">
<!--
There is no longer a need to hide scripts from old browsers. All user
agents currently in use understand the SCRIPT element.
//nº of pictures

var npic=Math.round(Math.random())

//name of pictures

namepics= new Array("1.jpg","2.jpg");

document.write("<img src='" + namepics[npic] + "' >");
[snip]
Unfortunatelly I haven´t figure out out to work with more than two images
tough


How about

var pics = ['1.jpg', '2.jpg', '3.jpg', '4.jpg' /* etc... */];
document.write('<img src="'
+ pics[Math.floor((Math.random() % 1) * pics.length)]
+ '" alt="">');

(Math.random() % 1) produces a real number in the range 0 <= n < 1. The
modulus ensures that buggy implementations don't return 1.0. Multiplying
by 'm' changes that range to 0 <= n < m. Using Math.ceil() then produces
an integer with a maximum value of (m - 1).

Of course, this doesn't actually change a background image. For this, use
the style object:

var b, s;
if((b = document.body) && (s = b.style)) {
var pics = ['1.jpg', '2.jpg', '3.jpg', '4.jpg' /* etc... */];
s.backgroundImage =
pics[Math.floor((Math.random() % 1) * pics.length)];
}

(untested)

Hope that helps,
Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #4

P: n/a
JRS: In article <41**********************@news.telepac.pt>, dated Fri,
24 Sep 2004 19:00:56, seen in news:comp.lang.javascript, Oscar Monteiro
<of**@hotmail.com> posted :
Again here is a solution that works perfectly for 5 (five)
images
<script language="Javascript">
Deprecated<!--
npic=Math.random()
if (npic < 0.2)
document.write("<img src=1.jpg>");
else if (npic <0.4)
document.write("<img src=2.jpg>");
else if (npic <0.6)
document.write("<img src=3.jpg>");
else if (npic <0.8)
document.write("<img src=4.jpg>");
else
document.write("<img src=5.jpg>");

//-->
</script>

But it would be much more elegant and extensible to use Random (FAQ
4.22) to generate the variable part of the array name :

document.write("img src=", Random(5)+1, ".jpg>")

or to index an array of names
var Arr = ["this", "that", "tother"]
document.write("img src=" + Arr[Random(Arr.length)] + ".jpg>")

In article <41**********************@news.telepac.pt>, dated Fri, 24 Sep
2004 17:15:13, seen in news:comp.lang.javascript, Oscar Monteiro
<of**@hotmail.com> posted :
var npic=Math.round(Math.random()) namepics= new Array("1.jpg","2.jpg");

document.write("<img src='" + namepics[npic] + "' >");


Let that be a lesson to those who think that Math.round with Math.random
is always wrong !

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #5

P: n/a
Oscar Monteiro wrote:
This Little script let you cicle between 2 images
<body>
<script language = "Javascript">
<script type="text/javascript">
<!--
Don't, there is no standard for this. More, it is obsolete
and can only get you in more trouble if the script engine
does not support the non-standard approach.
//nº of pictures

var npic=Math.round(Math.random())
Math.random() returns a floating-point number between 0 and 1.
Math.round(...) rounds that number to the next integer number,
i.e. `npic' can assume only one of the values 0 or 1. This
is pertinent for a two-element array, but it certainly is not
for arrays with a different length.
//name of pictures

namepics= new Array("1.jpg","2.jpg");
Variables should be declared using the `var' keyword to avoid
side effects in functions (omitting the `var' keyword always
declares globals).
document.write("<img src='" + namepics[npic] + "' >");

//-->
Don't, see above.
</script>
</body>

Unfortunatelly I haven´t figure out out to work with more than two images

^[1]

The reason is that your random number computation does not make any sense
with more than two elements in the array (indexes 0 and 1). Instead, you
should use the length of the array to compute an integer number in range:

var
namepics = new Array("1.jpg", "2. jpg", "3.jpg"),
npics = Math.round(Math.random() * namepics.length);
document.write('<img src="' + namepics[npic] + '" alt="...">');

(Don't forget the "alt" attribute, it is required for Valid HTML! For
reasonable and barrier-free authoring the array should hold an Object
object providing at least both the image filename and the alternative
text, such as

var namepics = [
{src: "1.jpg", alt: "one"},
{src: "2.jpg", alt: "two"},
{src: "3.jpg", alt: "three"}
];
...
document.write(
"<img src='" + namepics[npic].src
+ "' alt="' + namepics[npic].alt + '">');
)

Your second solution in <news:41**********************@news.telepac.pt>
works indeed, however it is hard to maintain as with every new image you
have to re-compute the fraction which an element needs to match; yet,
*computing* is what *computers* were built for.
PointedEars
___________
[1] Please declare your character set and don't use accents as apostrophes,
see <http://insideoe.tomsterdam.com/>.
--
Vacuume Cleaner for computers: format C:
Jul 23 '05 #6

P: n/a
JRS: In article <13****************@PointedEars.de>, dated Sun, 10 Oct
2004 15:16:05, seen in news:comp.lang.javascript, the infant Thomas
'PointedEars' Lahn <Po*********@web.de> posted, in response to an
article over a fortnight old, in a thread that was completed long ago :

The reason is that your random number computation does not make any sense
with more than two elements in the array (indexes 0 and 1). Instead, you
should use the length of the array to compute an integer number in range:

var
namepics = new Array("1.jpg", "2. jpg", "3.jpg"),
npics = Math.round(Math.random() * namepics.length);
document.write('<img src="' + namepics[npic] + '" alt="...">');


AIUI, the three elements of namepics are indexed 0, 1, 2;
namepics.length is 3, and npics will be assigned the values 0, 1, 2, 3
with probabilities about 17%, 33%, 33%, 17%.

Indexing namepics with npic gives an error message; with npics gives an
undefined element 16% of the time.

It is an elementary error; one that those who are familiar with
newsgroup FAQ item 4.22 should not be making. IMHO, "your random number
computation does not make any sense".

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #7

This discussion thread is closed

Replies have been disabled for this discussion.