473,464 Members | 1,588 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

need script to choose random background-image

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
6 2068
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
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
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
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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: Sticks | last post by:
ok... im not quite sure how to describe my problem. i have a php script that runs through my entire php site and writes the resulting output to html files. this is necessary as the nature of the...
4
by: Marquisha | last post by:
If this is off-topic, please forgive me. But I thought this might be the perfect spot to get some advice about how to proceed with a project. Working on a Web site design for a nonprofit...
4
by: Phillo | last post by:
Hello, I'm new at Javascript, and have written a script for a series of random roll-over button images, but one thing I would like to add is a function that checks to make sure that there are no...
14
by: Nikola | last post by:
I need a function that reads from a txt file and randomly chooses a line from which retrieves a string (with spaces) and returns it to main function. thx
13
by: Pedro Graca | last post by:
I'm sure this isn't very pythonic; comments and advice appreciated def curious(text): """ Return the words in input text scrambled except for the first and last letter. """ new_text = "" word...
3
by: Peter Michaux | last post by:
Hi, Since I can do this document.defaultView.getComputedStyle(el, null).height; why would I ever want to do this document.defaultView.getComputedStyle(el,...
2
by: sorobor | last post by:
dear sir .. i am using cakephp freamwork ..By the way i m begener in php and javascript .. My probs r bellow I made a javascript calender ..there is a close button ..when i press close button...
1
by: deepaks85 | last post by:
Dear All, I want to send some data through a form with Multiple attachment in an HTML Format. I have tried it but it is not working for me. I am able to send data without attachment but with the...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.