473,848 Members | 1,804 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

javascript to change cell background colours on a timer.

Hi All,

I want to write some javascript for a html page which does the
following.

Imagine that the page contains a table with 2 columns and 3 rows, e.g.:

+---+---+
| A | B |
+---+---+
| C | D |
+---+---+
| E | F |
+---+---+

and that the background colour for each cell is a different colour.

I want some javascript which will wait a given time, say 10 seconds,
then change the background colour of the cells. So that:

cell A gets cell C's colour
cell C gets cell E's colour
cell E gets cell F's colour
cell F gets cell D's colour
cell D gets cell B's colour
cell B gets cell A's (original) colour

or in other words, the background colours of cells rotate around
clockwise.

Can someone please post up some sample js code that will do this???

Also, I am hoping that this would not interfere with the user viewing
the page as per normal.

NB -- I'm a bit of a newbie at writing javascript. :-)

Regards,
Peter W. :-)))
Sandy Bay, Hobart, Tas, AU.

(delete silly boy to reply via email).
Jul 23 '05 #1
3 4776
Peter Williams wrote:
Hi All,

I want to write some javascript for a html page which does the
following.

Imagine that the page contains a table with 2 columns and 3 rows, e.g.:

+---+---+
| A | B |
+---+---+
| C | D |
+---+---+
| E | F |
+---+---+

and that the background colour for each cell is a different colour.

I want some javascript which will wait a given time, say 10 seconds,
then change the background colour of the cells. So that:

cell A gets cell C's colour
cell C gets cell E's colour
cell E gets cell F's colour
cell F gets cell D's colour
cell D gets cell B's colour
cell B gets cell A's (original) colour

or in other words, the background colours of cells rotate around
clockwise.

Can someone please post up some sample js code that will do this???

Also, I am hoping that this would not interfere with the user viewing
the page as per normal.

NB -- I'm a bit of a newbie at writing javascript. :-)

Regards,
Peter W. :-)))
Sandy Bay, Hobart, Tas, AU.

(delete silly boy to reply via email).


Just don't make it necessary for this to happen -- personally, this
kind of thing is very irritating for me to look at, and I tend to jump
right off any page that has flashies like this.

Not knowing how much of a newbie you are, I'm going to put this in
tutorial form because I like to think people would rather learn how to
do something than have it done for them. The sum total is at the bottom
if you want to skip straight to it. Don't.

First things first, ID each of the cells:
cellA, cellB, et cetera.

<td id=cellA>A</td>

To identify it within JavaScript, then, we might make a function to
provide some cross-compatibility:

var gid;
if( document.getEle mentById )
gid = function ( x ) {
return document.getEle mentById( x );
}

else
gid = function ( x ) {
return document.all[ x ];
}

-- this leaves out some older browsers, but people still using them are
probably used to being left out, by now.
Now, anytime you make a call like:

gid( 'cellA' );

You get back a reference to your cellA element.

To reference its background color, use: gid( 'cellA'
).style.backgro undColor

Now since this operation of moving colours about is going to be run
repeatedly, we'll make a function to do it.

function moveColors( ) {
// See below
}

Also since this is going to be run repeatedly, we probably don't want
to be making calls to our gid function too often or it'll slow things
down. We need a faster way to address our cells.

So we'll declare an array AFTER the document's loaded and load the
elements we want into it, like so (putting them in order according to
how we want the colors to move):

cells = [
gid( 'cellA' ), gid( 'cellC' ),
gid( 'cellE' ), gid( 'cellF' ),
gid( 'cellD' ), gid( 'cellB' )
];

If we tried to do this before the </table>, these cells wouldn't exist
and we'd have a bunch of errors instead, so we'll put this in a
function to be called once the document is loaded.

function docLoaded( ) {
cells = [
gid( 'cellA' ), gid( 'cellC' ),
gid( 'cellE' ), gid( 'cellF' ),
gid( 'cellD' ), gid( 'cellB' )
];

}

We'll run into a problem later: since I'm not going to use inline CSS
to set the colours (and you shouldn't either), the value of the
style.backgroun dColor won't be set right off. Only the
currentStyle.ba ckgroundColor will be.

So we add a few more lines to docLoaded( ):
function docLoaded( ) {
cells = [
gid( 'cellA' ), gid( 'cellC' ),
gid( 'cellE' ), gid( 'cellF' ),
gid( 'cellD' ), gid( 'cellB' )
];

for( var c = 0; c < cells.length; c++ ) {
cells[ c ].style.backgrou ndColor =
cells[ c ].currentStyle.b ackgroundColor;

cells[ c ] = cells[ c ].style;
}
}

That last line is mostly so we don't have to keep typing .style all
over the place.
Now we start filling out the function to moveColors.

Thinking logically, if we just start moving the colours around, one of
them is going to get lost.

colour of A = colour of C
colour of C = colour of D
....
colour of B = colour of A? By this point, A was already changed. You
already pointed this out yourself.

So we'll have to store A before changing it.

var colorofA = cells[ 0 ].backgroundColo r;

Then we move colours around. Easiest way is to use a loop, but we want
the loop to stop on the second-to-last cell, because the last is a
special case (there are no cells after it).
for( var c = 0; c < cells.length - 1; c++ )
cells[ c ].backgroundColo r = cells[ c + 1 ].backgroundColo r;

Then handle the special case:
cells[ cells.length - 1 ].backgroundColo r = colorofA;
Our moveColors function now looks like this:

function moveColors() {
var colorofA = cells[ 0 ].backgroundColo r;

for( var c = 0; c < cells.length - 1; c++ )
cells[ c ].backgroundColo r = cells[ c + 1 ].backgroundColo r;

cells[ cells.length - 1 ].backgroundColo r = colorofA;
}

(Note that you can speed it up a little more by not checking
cells.length so often.)
Now to get it moving, I recommend a setInterval. Others might recommend
a setTimeout, and they probably have good reason to do so, so I'm going
to show you how to do that.

setTimeout works like this:
var T = setTimeout( strCode, intInterval );

strCode = code to be executed.
intInterval = milliseconds to wait.
T = the 'process ID' of the timeout.
So, in this case, to make it run moveColors a half-second from now,
you'd do something like this:

T = setTimeout( moveColors, 500 );

Since you want it to run EVERY half-second, you'll put something
similar in the moveColors function, just before the } that ends it.

function moveColors() {
var colorofA = cells[ 0 ].backgroundColo r;

for( var c = 0; c < cells.length - 1; c++ )
cells[ c ].backgroundColo r = cells[ c + 1 ].backgroundColo r;

cells[ cells.length - 1 ].backgroundColo r = colorofA;

T = setTimeout( moveColors, 500 );
}

We'll also put one in the docLoaded function to get it started
automatically.
So here's what we've got in total:
<html>
<head>
<style type=text/css>

#cellA { background-color: red; }
#cellB { background-color: blue; }
#cellC { background-color: green; }
#cellD { background-color: yellow; }
#cellE { background-color: cyan; }
#cellF { background-color: magenta; }

</style>
<script type=text/javascript>

var T; // The PID of the moveColors timeout
var gid; // our own getElementById
var cells; // the list of table cells for easy, speedy reference
if( document.getEle mentById )
gid = function ( x ) {
return document.getEle mentById( x );
}

else
gid = function ( x ) {
return document.all[ x ];
}

function moveColors() {
var colorofA = cells[ 0 ].backgroundColo r;

for( var c = 0; c < cells.length - 1; c++ )
cells[ c ].backgroundColo r = cells[ c + 1 ].backgroundColo r;

cells[ cells.length - 1 ].backgroundColo r = colorofA;

T = setTimeout( moveColors, 500 );

}

function docLoaded( ) {
cells = [
gid( 'cellA' ), gid( 'cellC' ),
gid( 'cellE' ), gid( 'cellF' ),
gid( 'cellD' ), gid( 'cellB' )
];

for( var c = 0; c < cells.length; c++ ) {
cells[ c ].style.backgrou ndColor =
cells[ c ].currentStyle.b ackgroundColor;

cells[ c ] = cells[ c ].style;
}

T = setTimeout( moveColors, 500 );
}
</script>
</head>
<body onLoad=docLoade d()>
<table>
<tr>
<td id=cellA>A</td>
<td id=cellB>B</td>
<tr>
<td id=cellC>C</td>
<td id=cellD>D</td>
</tr>
<tr>
<td id=cellE>E</td>
<td id=cellF>F</td>
</tr>
</table>
</body>
</html>

Jul 23 '05 #2

"Peter Williams" <pe**********@b igpond.boy.net. au> wrote in message
news:c1******** *********@news-server.bigpond. net.au...
Hi All,

I want to write some javascript for a html page which does the
following.

Imagine that the page contains a table with 2 columns and 3 rows, e.g.:

+---+---+
| A | B |
+---+---+
| C | D |
+---+---+
| E | F |
+---+---+

and that the background colour for each cell is a different colour.

I want some javascript which will wait a given time, say 10 seconds,
then change the background colour of the cells. So that:

cell A gets cell C's colour
cell C gets cell E's colour
cell E gets cell F's colour
cell F gets cell D's colour
cell D gets cell B's colour
cell B gets cell A's (original) colour

or in other words, the background colours of cells rotate around
clockwise.

Can someone please post up some sample js code that will do this???

Also, I am hoping that this would not interfere with the user viewing
the page as per normal.

NB -- I'm a bit of a newbie at writing javascript. :-)

Regards,
Peter W. :-)))
Sandy Bay, Hobart, Tas, AU.

(delete silly boy to reply via email).

here's a lazy way to do it,

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<html>
<head>
<title>Untitled </title>

<script language="JavaS cript" type="text/javascript">
function init() {
document.getEle mentById("r1c1" ).style.backgro undColor = "red";
document.getEle mentById("r1c2" ).style.backgro undColor = "blue";
document.getEle mentById("r2c1" ).style.backgro undColor = "green";
document.getEle mentById("r2c2" ).style.backgro undColor = "yellow";
document.getEle mentById("r3c1" ).style.backgro undColor = "orchid";
document.getEle mentById("r3c2" ).style.backgro undColor = "orange";
var timerid = setTimeout('swi tchcolors()',10 00);
}
function switchcolors() {
var savecolor = document.getEle mentById("r1c1" ).style.backgro undColor;
document.getEle mentById("r1c1" ).style.backgro undColor =
document.getEle mentById("r2c1" ).style.backgro undColor;
document.getEle mentById("r2c1" ).style.backgro undColor =
document.getEle mentById("r3c1" ).style.backgro undColor;
document.getEle mentById("r3c1" ).style.backgro undColor =
document.getEle mentById("r3c2" ).style.backgro undColor;
document.getEle mentById("r3c2" ).style.backgro undColor =
document.getEle mentById("r2c2" ).style.backgro undColor;
document.getEle mentById("r2c2" ).style.backgro undColor =
document.getEle mentById("r1c2" ).style.backgro undColor;
document.getEle mentById("r1c2" ).style.backgro undColor = savecolor;
var timerid = setTimeout('swi tchcolors()',10 00);
}
</script>
</head>

<body onload=init()>
<table>
<tr><td id=r1c1>A</td><td id=r1c2>B</td></tr>
<tr><td id=r2c1>C</td><td id=r2c2>D</td></tr>
<tr><td id=r3c1>E</td><td id=r3c2>F</td></tr>
</table>
</body>
</html>
Jul 23 '05 #3
Peter Williams wrote:
Hi All,

I want to write some javascript for a html page which does the
following.

Imagine that the page contains a table with 2 columns and 3 rows, e.g.:

+---+---+
| A | B |
+---+---+
| C | D |
+---+---+
| E | F |
+---+---+

and that the background colour for each cell is a different colour.

I want some javascript which will wait a given time, say 10 seconds,
then change the background colour of the cells. So that:

cell A gets cell C's colour
cell C gets cell E's colour
cell E gets cell F's colour
cell F gets cell D's colour
cell D gets cell B's colour
cell B gets cell A's (original) colour

or in other words, the background colours of cells rotate around
clockwise.

Can someone please post up some sample js code that will do this???

Also, I am hoping that this would not interfere with the user viewing
the page as per normal.

NB -- I'm a bit of a newbie at writing javascript. :-)

Regards,
Peter W. :-)))
Sandy Bay, Hobart, Tas, AU.

(delete silly boy to reply via email).


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<style type="text/css">

#marquee {
width: 120px;
margin: 100px auto;
border-collapse: collapse;
}
#marquee td {
width: 20px;
height: 20px;
border: 3px #fff inset;
background: #000;
}

</style>
<script type="text/javascript">

var colors = [];
var cells = [];

function init(table_id)
{
var table, trs, tr, r = 0, tds, td, c;
if (document.getEl ementById
&& (table = document.getEle mentById(table_ id))
&& (trs = table.rows))
{
tr = trs[r];
tds = tr.cells;
for (c = 0, cs = tds.length; c < cs; ++c)
{
cells.push(td = tds[c]); //top row
colors.push(td. style.backgroun d); //BGs
}
for (r = 1, rs = trs.length - 1; r < rs; ++r)
{
tr = trs[r];
tds = tr.cells;
cells.push(td = tds[tds.length - 1]); //right side
colors.push(td. style.backgroun d);
}
tr = trs[rs];
tds = tr.cells;
for (c = tds.length - 1; c > 0; --c)
{
cells.push(td = tds[c]); //bottom row
colors.push(td. style.backgroun d);
}
for (r; r > 0; --r)
{
tr = trs[r];
tds = tr.cells;
cells.push(td = tds[0]); //left side
colors.push(td. style.backgroun d);
}
}
T_marquee();
}

Array.prototype .rotate = function() //extension
{
this.unshift(th is.pop());
return this;
}

function T_marquee()
{
for (var i = 0, l = cells.length; i < l; ++i)
cells[i].style.backgrou nd = colors[i];
colors.rotate() ;
}

window.onload = function()
{
init('marquee') ;
window.intID = null;
intID = window.setInter val('T_marquee( )', 1000);
}

window.onunload = function() //intervals==scar y
{
if (intID)
clearInterval(i ntID);
}

</script>
</head>
<body>
<table id="marquee" cellspacing="1" >
<tbody>
<tr>
<td style="backgrou nd:#cc8;"></td>
<td style="backgrou nd:#8cc;"></td>
<td style="backgrou nd:#8c8;"></td>
<td style="backgrou nd:#da5;"></td>
<td style="backgrou nd:#889;"></td>
<td style="backgrou nd:#a94;"></td>
</tr><tr>
<td style="backgrou nd:#8e6;"></td>
<td></td><td></td><td></td><td></td>
<td style="backgrou nd:#88e;"></td>
</tr><tr>
<td style="backgrou nd:#e6c;"></td>
<td></td><td></td><td></td><td></td>
<td style="backgrou nd:#f93;"></td>
</tr><tr>
<td style="backgrou nd:#cc0;"></td>
<td></td><td></td><td></td><td></td>
<td style="backgrou nd:#ebf;"></td>
</tr><tr>
<td style="backgrou nd:#ee7;"></td>
<td></td><td></td><td></td><td></td>
<td style="backgrou nd:#9b4;"></td>
</tr><tr>
<td style="backgrou nd:#b0b;"></td>
<td style="backgrou nd:#8b5;"></td>
<td style="backgrou nd:#9fc;"></td>
<td style="backgrou nd:#cd6;"></td>
<td style="backgrou nd:#e99;"></td>
<td style="backgrou nd:#48a;"></td>
</tr>
</tbody>
</table>
</body>
</html>

Should work with any (reasonably symmetrical) table. No ids necessary.
Nothing wrong with inline CSS, used judiciously. Hope this isn't
homework. Cheers.

Jul 23 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

53
5771
by: Cardman | last post by:
Greetings, I am trying to solve a problem that has been inflicting my self created Order Forms for a long time, where the problem is that as I cannot reproduce this error myself, then it is difficult to know what is going on. One of these Order Forms you can see here... http://www.cardman.co.uk/orderform.php3
4
7439
by: Robert | last post by:
Hi, I am trying to add a background to a cell that contains multiple horizontal coloured layers on top of eachother. I managed to do this in IE, but firefox displays something very different so I would like to know if my HTML is in error or firefox. This is my HTML
19
2111
by: Stimp | last post by:
preferably one that when clicked can update three date dropdowns (day, month, year) like http://www.visitdublin.com/carhire/avis.asp Don't mind paying for the file... anyone seen something like this? -- "I hear ma train a comin' .... hear freedom comin"
5
2565
by: googlegroups | last post by:
I have a large table in html created dynamically. This table can grow to several hundred rows or more. I have the ability to hide or display individual rows (using row.style.display = "none") and this works well in both IE and Firefox. I would also like to do the same with columns as well. I did some research and col and colgroup nodes are not supported fully in both browsers. Also, doing "visibility: hidden" and sometimes "display:...
5
2935
by: nivas.meda | last post by:
Hi, I have an excel sheet with a graph and cells.If i change the value in the excel cells the graph will reflect.Now i am going to implement this functionality in html page.I successfully saved this as interactive html page.Now my requirement changes a bit.The excell cells will not visible to others.i have a text box,If i change the value in text box the excel template cell value need to change. I did the follwing steps for creating...
1
2233
by: Amirallia | last post by:
Hello, If I want to print a page with a table with cells colored in differents colors, assuming default settings in browser, when I view the page, all the colours disappear. I know that one of the default settings in my browser is 'don't print out the background colour' which is fine because this would use lots of ink, but my table cell colours anr not showing up. A idea is to replace the cell color with image, but I don't want to use
4
2162
by: Lachlan Hunt | last post by:
Hi, I'm looking for an interoperable method of determining the current background colour of an element that is set using an external stylesheet. I've tried: elmt.style.backgroundColor; but that only works if the colour has been set using the style attribute or previously set using script. I've also tried:
12
2095
by: shafiqrao | last post by:
Hello everyone, I have a script that runs in IE great, but in firefox it has problems. I understand that there are some objects that are accessed differently in IE and Mozilla. Can anybody let me know what I need to change in the file to make a copy that would run fine on Firefox? Here is the link to the file: http://people.emich.edu/srehman2/study/polls.html click on the 'Build Bars' link displayed at the top-right corner. I am...
2
22077
by: Mark | last post by:
IE creates an object of every ID'd HTML tag (so it appears), and each object sets a property for any parameter I set in the tag. For example, my HTML might be: <td id='cell1' background='myimg.jpg' width='30'... </tdwhich IE will use to create a Javascript object called 'cell1' with properties of background and width, like so: cell1.background would have a value of 'myimg.jpg' and cell1.width would have a value of 30. I can change the...
0
9893
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9738
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10348
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9500
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7894
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7069
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5919
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4137
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3175
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.