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

Q: Automatically Changing Background Color of a Table Cell?

P: n/a
I'm the webmaster for a recreational organization. As part of one page of the
site, I have an HTML "Calendar at a Glance" of the organization's events for
the month. It's a simple table of a calendar, 7 across by whatever needed
down, and I manually create it each month - not a big deal.

Every day I go in and darken the background color of the current day's cell
by changing the appropriate <TD> entry to <TD bgcolor="c63800"> and uploading
the page. Takes well under a minute start to finish. Thus the calendar
gradually changes color over the course of the month, with the past dates dark
and the future dates lighter and thus more apparent to the eye.

But I have to ask if there's a nifty way in which this might be done
automatically, based on the current day and the number (the day of the month)
that follows the <TD> entry.

A typical "before" entry is

<TD>23<br>Peet's Coffee, Newport Beach<br><br>8 AM: Don<br>9 AM: Molly</TD>

and an "after" entry is

<TD bgcolor="c63800">23<br>Peet's Coffee, Newport Beach<br><br>8 AM: Don<br>9
AM: Molly</TD>

I don't pretend to be a javascript heavy, but can usually stumble my way
through a task given some words of wisdom. Is this "doable"?



Art
Temporary usercode - to be deleted when spam starts. Use MyBrainHurts at this ISP to reach me
Jul 23 '05 #1
Share this Question
Share on Google+
31 Replies


P: n/a
Ivo
"Arthur Shapiro" wrote
Every day I go in and darken the background color of the current day's cell by changing the appropriate <TD> entry to <TD bgcolor="c63800">
But I have to ask if there's a nifty way in which this might be done
automatically, based on the current day and the number (the day of the
month) that follows the <TD> entry.
A typical "before" entry is

<TD>23<br>Peet's Coffee, Newport Beach<br><br>8 AM: Don<br>9
AM: Molly</TD>

and an "after" entry is

<TD bgcolor="c63800">23<br>Peet's Coffee, Newport Beach<br><br>8
AM: Don<br>9 AM: Molly</TD>


First thought is to automate this on the server of course, but you don't
seem to do anything serverside. Turning to javascript for this will leave
users who have no javascript with a dull calendar where every day looks the
same.
Second thought is to use a class rather than bgcolor and specify the color
in a stylesheet. Not sure about the direct benefit of this tho.

Well, if all days start with the date's number right after the <TD> opening
tag (even whitespace in between may be a problem for some browsers) and the
whole table has an id, such as <table id="calendar">, then you could put
this right after the </table> tag:

<script type="text/javascript">
var now=new Date().getDate();
var td=document.getElementById('calendar').cells, i=td.length;
while ( i-- ) {
if ( td[i].firstChild.nodeValue <= now ){ td[i].bgColor = '#c63800'; }
}
</script>

td[n].firstChild would be the textnode, its value the text, ie. everything
up to the first <br>. This is compared to the variable "now", which today
for example is 29, and if smaller or equal (you say you change the current
day), the color is applied to the cell. Marking today in gold would take one
more line:
if ( td[i].firstChild.nodeValue < now ){ td[i].bgColor = '#c63800'; }
if ( td[i].firstChild.nodeValue == now ){ td[i].bgColor = '#ffd700'; }

hth
--
Ivo

Jul 23 '05 #2

P: n/a
In article <41**********************@news.wanadoo.nl>, "Ivo" <no@thank.you> wrote:
Well, if all days start with the date's number right after the <TD> opening
tag (even whitespace in between may be a problem for some browsers) and the
whole table has an id, such as <table id="calendar">, then you could put
this right after the </table> tag:

<script type="text/javascript">
var now=new Date().getDate();
var td=document.getElementById('calendar').cells, i=td.length;
while ( i-- ) {
if ( td[i].firstChild.nodeValue <= now ){ td[i].bgColor = '#c63800'; }
}
</script>


Very, very interesting...thank you! My only problem is that this script
happens to also change the color of the heading line that spans the top width
of the table ("December at a Glance") and the cells "Sunday"..."Saturday" that
are the top row above the actual date cells. But I think this gives me enough
ammunition to work with, to see if I can avoid affecting cells whose data
doesn't start with numeric tokens.

I'm most appreciative of your excellent suggestions. Clearly I'm going to
have to learn some more of this scripting "magic".

I guess the one laughably silly question is why the script should follow the
table in question; I don't appreciate yet when something goes fairly globally
in the html document, and when it immediately precedes or immediately follows
information in the document.

Art
Temporary usercode - to be deleted when spam starts. Use MyBrainHurts at this ISP to reach me
Jul 23 '05 #3

P: n/a
Ivo
"Arthur Shapiro" wrote
"Ivo" wrote:
Well, if all days start with the date's number right after the <TD> openingtag (even whitespace in between may be a problem for some browsers) and thewhole table has an id, such as <table id="calendar">, then you could put
this right after the </table> tag:

<script type="text/javascript">
var now=new Date().getDate();
var td=document.getElementById('calendar').cells, i=td.length;
while ( i-- ) {
if ( td[i].firstChild.nodeValue <= now ){ td[i].bgColor = '#c63800'; }
}
</script>
Very, very interesting...thank you! My only problem is that this script
happens to also change the color of the heading line that spans the top

width of the table ("December at a Glance") and the cells "Sunday"..."Saturday" that

Semantically speaking, shouldn't those cells be TH rather than TD elements?
That would exclude them from the coloring function, and you can style them
separately with CSS.
I guess the one laughably silly question is why the script should follow the table in question; I don't appreciate yet when something goes fairly globally in the html document, and when it immediately precedes or immediately follows information in the document.


The script as is runs when the browsers finds it, because it is not put in a
function. The statements are simply there to be executed straight away. You
could wrap the whole in a function, put that function in the document's head
or an included file and call it onload. The only important thing is that the
element with id 'calendar' has to be there before the script sets off to
avoid error and failure. That is why I suggest putting the script after the
table, that way you can run it *before* the page finishes loading and most
users will never even see the uncolored table.

Ivo
Jul 23 '05 #4

P: n/a
In article <41***********************@news.wanadoo.nl>, "Ivo" <no@thank.you> wrote:
Semantically speaking, shouldn't those cells be TH rather than TD elements?
That would exclude them from the coloring function, and you can style them
separately with CSS.


The Day names are, in fact, TH elements. They still seem to have been
affected by the script. But I'll klutz around as time permits - I'm sure this
can be made to work. If you care, the calendar is on the page
http://www.ocrebels.com/rides.htm although that page does not include your
script - I'm obviously going to work with it at my end until it functions as I
desire.

Art
Temporary usercode - to be deleted when spam starts. Use MyBrainHurts at this ISP to reach me
Jul 23 '05 #5

P: n/a
Ivo
"Arthur Shapiro" wrote
"Ivo" wrote:
Semantically speaking, shouldn't those cells be TH rather than TD elements?That would exclude them from the coloring function, and you can style themseparately with CSS.
The Day names are, in fact, TH elements. They still seem to have been
affected by the script.


My mistake. I was mixed up between x.getElementsByTagName('td') and x.cells
which also collects TH elements. The first is the standard way, but the
latter is much faster and better supported among browsers.
But I'll klutz around as time permits - I'm sure this
can be made to work.


Without doubt:

while ( i-- ) {
day=td[i].firstChild.nodeValue;
if ( /^\d/.test(day) && day <= now ){ td[i].bgColor = '#c63800'; }
}

The bit that reads /^\d/.test(day) is a regular expression which will
evaluate to true for strings starting with a digit and false otherwise. This
should solve the issue as long the content in the TH cells starts with
letters. I have copied your table together with the script to a temporary
testpage at http://4umi.com/web/javascript/arthur.htm; the changes to the
HTML I made were adding the id to the table, correcting a typo at 8 December
and removing all bgcolors.
hth
--
Ivo
Jul 23 '05 #6

P: n/a
Ivo wrote:
<snip>
<script type="text/javascript">
var now=new Date().getDate();
var td=document.getElementById('calendar').cells, i=td.length;
while ( i-- ) {
if ( td[i].firstChild.nodeValue <= now ){ td[i].bgColor =
'#c63800';
}
}

<snip>

Doesn't - getDate - return the (client) local date? I would have thought
that there is a time zone problem in this script (that may elude the OP
if not mentioned, as local testing would not expose it).

Richard.
Jul 23 '05 #7

P: n/a
Ivo wrote:
"Arthur Shapiro" wrote
"Ivo" wrote:
Semantically speaking, shouldn't those cells be TH rather than TD
elements?
That would exclude them from the coloring function, and you can style
them
separately with CSS.


The Day names are, in fact, TH elements. They still seem to have been
affected by the script.

My mistake. I was mixed up between x.getElementsByTagName('td') and x.cells
which also collects TH elements. The first is the standard way, but the
latter is much faster and better supported among browsers.


Another way is to put the heading stuff in a thead element, then put
the dates in a tbody. Locate the tbody using the script and go from
there. It will exclude any elements in the thead or tfoot.

Incidentally, tables are supposed to have tbody tags, but since almost
no one puts them in the HTML, browsers just put 'em where it seems
appropriate.

--
Rob
Jul 23 '05 #8

P: n/a
In article <41***********************@news.wanadoo.nl>, "Ivo" <no@thank.you> wrote:
Without doubt:

while ( i-- ) {
day=td[i].firstChild.nodeValue;
if ( /^\d/.test(day) && day <= now ){ td[i].bgColor = '#c63800'; }
}

Thank you again! I was going to fool with regular expressions after work
today, and you beat me to it.

Your table displays cleanly in IE, but not in Firefox. I'll be checking my
settings later today. And there's some additional corruption in Firefox. But
I'm sure I can reason things out at this point. This has all been very
interesting, and tells me that the more Javascript I can learn, the better
things will be.

The comment about time zones was valid, but fortunately not a realistic
concern for our local organization.

I'm most appreciative of the assistance.

Art
Temporary usercode - to be deleted when spam starts. Use MyBrainHurts at this ISP to reach me
Jul 23 '05 #9

P: n/a
Arthur Shapiro wrote:
[...]
Your table displays cleanly in IE, but not in Firefox. I'll be checking my
settings later today. And there's some additional corruption in Firefox. But


Try:

if ( /^\d/.test(day) && day <= now ) {
td[i].style.backgroundColor = '#c63800';
}

--
Fred
Jul 23 '05 #10

P: n/a
Lee
Fred Oz said:

Arthur Shapiro wrote:
[...]
Your table displays cleanly in IE, but not in Firefox. I'll be checking my
settings later today. And there's some additional corruption in Firefox. But


Try:

if ( /^\d/.test(day) && day <= now ) {
td[i].style.backgroundColor = '#c63800';
}


I may have overlooked something, but isn't (day <= now) going to be evaluated as
a string comparison? That would give surprising results on January 2.

Jul 23 '05 #11

P: n/a
JRS: In article <cq*******************@news.demon.co.uk>, dated Wed, 29
Dec 2004 07:26:53, seen in news:comp.lang.javascript, Richard Cornford
<Ri*****@litotes.demon.co.uk> posted :
Ivo wrote:
<snip>
<script type="text/javascript">
var now=new Date().getDate();
var td=document.getElementById('calendar').cells, i=td.length;
while ( i-- ) {
if ( td[i].firstChild.nodeValue <= now ){ td[i].bgColor =
'#c63800';
}
}

<snip>

Doesn't - getDate - return the (client) local date? I would have thought
that there is a time zone problem in this script (that may elude the OP
if not mentioned, as local testing would not expose it).


An American recreational organisation probably ignores distant parts of
the country, let alone the rest of the world.

But one wonders whether the code includes 864e5 or the equivalent; and,
if so, whether it does so safely.

--
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 #12

P: n/a
JRS: In article <cq*********@drn.newsguy.com>, dated Wed, 29 Dec 2004
08:28:07, seen in news:comp.lang.javascript, Lee
<RE**************@cox.net> posted :
Fred Oz said:

Arthur Shapiro wrote:
[...]
Your table displays cleanly in IE, but not in Firefox. I'll be checking my
settings later today. And there's some additional corruption in Firefox. But


Try:

if ( /^\d/.test(day) && day <= now ) {
td[i].style.backgroundColor = '#c63800';
}


I may have overlooked something, but isn't (day <= now) going to be evaluated as
a string comparison? That would give surprising results on January 2.

If so, assuming variable now to be an integer, using +day should
suffice; also untested.

--
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 #13

P: n/a
I've been poking around on the web for a couple days, and aside from a few
vauge reports of folks having trouble with firstchild with Mozilla and
Firefox, I haven't really gotten anywhere. Do any of you "heavies" have some
advice? Again, the suggested constructs seem to work as expected in IE, but
not in Mozilla/Firefox. I haven't tried Opera but this is sufficiently a
show-stopper to not proceed further. Am I doomed?

A second question. I went to my bookshelf, which includes both HTML and
Javascript references, and found absolutely nothing on FirstChild and its
various methods and subfields such as NodeValue. Does anyone have any
favorite references? I'm happy to purchase a couple of books that might be
recommended.
Art
Temporary usercode - to be deleted when spam starts. Use MyBrainHurts at this ISP to reach me
Jul 23 '05 #14

P: n/a
Arthur Shapiro wrote:
<snip>
... . Do any of you "heavies"
have some advice? ...

<snip>

If you like: Stop vaguely talking about problems you are having and
instead create and present a functional minimal test-case that
demonstrates it in isolation (along with an exact and specific
description of what it is intended to demonstrate).

Richard.
Jul 23 '05 #15

P: n/a
In article <cr*******************@news.demon.co.uk>, "Richard Cornford" <Ri*****@litotes.demon.co.uk> wrote:
-->: Stop vaguely talking about problems you are having and
instead create and present a functional minimal test-case that
demonstrates it in isolation (along with an exact and specific
description of what it is intended to demonstrate).


OK, fair enough - as it had only been a couple of days I was working under the
assumption that it was a "current" topic.

Take a look at the minimal test case:

http://www.ocrebels.com/javascripttest.htm

This is one row of an html table-based calendar, with javascript courtesy of a
very helpful participant in this forum. The script is intended to change the
bgcolor of cells representing dates prior to today's date.

It does, in Internet Explorer.

It doesn't in Mozilla or Firefox. About the only obvious curiosity is that
the Mozilla javascript console reports "td has no properties" - which is
certainly true.

So the apparent question is: "is there something I need to know about
Javascript as implemented for Mozilla/Firefox, so I can achieve the same
functionality as seems to occur with IE?"


Art
Temporary usercode - to be deleted when spam starts. Use MyBrainHurts at this ISP to reach me
Jul 23 '05 #16

P: n/a
Ivo
"Arthur Shapiro" wrote
I've been poking around on the web for a couple days, and aside from a few
vauge reports of folks having trouble with firstchild with Mozilla and
Firefox, I haven't really gotten anywhere.
Again, the suggested constructs seem to work as expected in IE,
but not in Mozilla/Firefox. I haven't tried Opera.
Changing
document.getElementById('calendar').cells
to
document.getElementById('calendar').getElementsByT agName('td')

has made also Mozilla 1.0 understand the idea. Haven't tried other browsers.
I find it strange that we must resort to getElementsByTagName when the good
ol' TABLE DOM provides such excellent collections as x.rows and x.cells.
Perhaps they only exist if you access the calendar not by its id but as a
table:

document.getElementsByTagName('table')[0].cells // or 1 or 2 or ..

Perhaps the problem lies with the fact that the code dicussed earlier here
doesnot currently include proper feature detection or any error trapping.
Using getElementById, one should always test not only the id in question,
but also the existence of the method:

if( document.getElementById && document.getElementById('someid') )

Likewise, using firstChild.NodeValue, we should perhaps test the existence
of the firstChild before accessing its nodeValue. In our case, an empty cell
such as the days in November might lead Mozila to believe it should error
because td[i].firstChild is null and it has no nodeValue property to look
into. The syntax:

day=td[i].firstChild && td[i].firstChild.nodeValue;

because tests /evaluate/ to true or false, but /return/ the actual test
value. Here the outcome might become either a variable of type 'string' with
some text from the cell, or a variable of type 'null' if that 's what
td[i].firstChild is. And comparing null with the date number is just fine in
this table. After all:

(null < 1) === true;
A second question. I went to my bookshelf, which includes both HTML and
Javascript references, and found absolutely nothing on FirstChild and its
various methods and subfields such as NodeValue. Does anyone have any
favorite references?


Note that javascript is case-sensitive. This means firstchild and FirstChild
are not the same thing. In fact, neither is anything by default. The element
known to the DOM as x.firstChild (small f, capital C) is shorthand for
x.childNodes[0], ie. the first element -- or node -- that is a sub-element
of x. Look for javascript+firstChild on the web, plenty of examples can be
found, including <
http://www.zvon.org/xxl/DOM2referenc...s/Node_firstCh
ild.html >. The specification about nodes and their properties can be found
at < http://www.w3.org/TR/DOM-Level-2-Cor...#ID-1950641247 >.

Strictly speaking, elements and nodes are not the same thing. Nodes can be
of type element (say HTML tags), in which they may contain other nodes, or
they are the bits of text between the actual tags. And also:

x.lastChild === x.childNodes[x.childNodes.length-1];

I updated the tstpage < http://4umi.com/web/javascript/arthur.htm > with the
Mozilla1.0 code.

Happy '05,
--
Ivo
Jul 23 '05 #17

P: n/a
Ivo wrote:
<snip>
Changing
document.getElementById('calendar').cells
to
document.getElementById('calendar').
getElementsByTagName('td')

has made also Mozilla 1.0 understand the idea. Haven't tried
other browsers. I find it strange that we must resort to
getElementsByTagName when the good ol' TABLE DOM provides
such excellent collections as x.rows and x.cells. ...

<snip>

The 'TABLE DOM'? The W3C HTML DOM specifies a - rows - property of the
HTMLTableElement interface but a - cells - collection is only to be
found on HTMLTableRowElement. A usual Mozilla/FireFox is following the
specification, but not providing all of the 'convenience' properties
that IE implements in addition.

Richard.
Jul 23 '05 #18

P: n/a
Arthur Shapiro wrote:
<snip>
Take a look at the minimal test case:

http://www.ocrebels.com/javascripttest.htm

<snip>

No, I read news off-line.

Richard.
Jul 23 '05 #19

P: n/a
In article <41***********************@news.wanadoo.nl>, "Ivo" <no@thank.you> wrote:

Changing
document.getElementById('calendar').cells
to
document.getElementById('calendar').getElementsByT agName('td')

has made also Mozilla 1.0 understand the idea.
Thank you once again, and I'm going to carefully consider the remainder of
your message. I feel the absence of having a good, accessible reference
forced me to request help where it might not otherwise have been necessitated.
The URL you suggested will be scrutinized.

A general question: as you can tell, I'm a javascript novice (although a
software engineer with decades of experience). What sort of tools are
available for stepping through and otherwise debugging a small script such as
the one in question? That seems like a practical way to pick up this stuff.
Clearly it takes time and a lot of false steps to reach your obvious level of
proficiency.

Art
Temporary usercode - to be deleted when spam starts. Use MyBrainHurts at this ISP to reach me
Jul 23 '05 #20

P: n/a
JRS: In article <di3Bd.63892$QR1.37398@fed1read04>, dated Fri, 31 Dec
2004 03:01:31, seen in news:comp.lang.javascript, Arthur Shapiro
<ar***********@cox.net> posted :
A general question: as you can tell, I'm a javascript novice (although a
software engineer with decades of experience). What sort of tools are
available for stepping through and otherwise debugging a small script such as
the one in question? That seems like a practical way to pick up this stuff.
Clearly it takes time and a lot of false steps to reach your obvious level of
proficiency.


With that experience, you may well recall punched cards and the daily
test run.

Firstly, be sure that in initial code development you are as far away
from that state as possible. No uploading, for example; just have a
browser and a backing-up editor open side-by-side on the same file, so
that you can edit-save-refresh within seconds.

Indeed, with a local copy (to save our bandwidth) of <URL:http://www.mer
lyn.demon.co.uk/js-quick.htm> one can just edit-test-edit for simple
code.

With a rapid test cycle, you can add only the minimum code at one time;
if you can test something after ten keystrokes, the number of possible
errors is greatly reduced. You can also use alert(X) freely, to verify
values; and comment it out or drag it away when not immediately wanted.

If the script uses a form, pre-load the input controls while testing by
using 'value="<default>"' and 'checked', so that the point at issue can
be re-tested without re-typing data.

You will have noticed that most script, here and on the Web, uses
excessive code repetition. ISTM that modularising into small functions
that can be tested independently, even if some are only called at one
location, is at least as useful in javascript as it is elsewhere.

Use validators frequently.

Others will no doubt write of tools outside editor-&-basic-browser.
However, it might have been well to say what browser(s) you have to
hand. Since so many things are, internationally, different from what
they may be in your unspecified country, it would be well to give your
approximate location; even if your code is intended to be international,
your habits may remain local.
Remember that all the code in a page is downloaded, perhaps over slow
dial-up. Therefore, eschew bloated functions with numerous options of
which any given page needs only one or two.
See the newsgroup FAQ & notes; and try my site.

--
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 #21

P: n/a
In article <RL**************@merlyn.demon.co.uk>, Dr John Stockton <sp**@merlyn.demon.co.uk> wrote:
With that experience, you may well recall punched cards and the daily
test run.

Yep! (not to mention paper tape).

At the risk of overextending my welcome, your very comprehensive response
about code development doesn't seem to address one concern that I suspect
isn't unique to my own situation: how does one address behavioral differences
among browsers? The previous discussion of my personal calendar script got
into this, where something simply didn't work in Foxfire although it worked
fine in IE. Ivo gave a different approach that worked, and I happily used it,
but I don't know how I would have attacked the problem myself.

I just tried to diddle the code so that the "empty" squares that round out the
start and the end of the month in my calendar table would be automatically
colored. I made the previously discussed code an "else" block, using the
following code for the "if" block:

if (td[i].innerText=="")
{ td[i].bgColor = '#c63800'; }

Works like a champ in IE, but once again it does absolutely zilch in Mozilla.
I just don't yet have a feel for the necessary technique / discipline in
dealing with an issue like this

Art
Temporary usercode - to be deleted when spam starts. Use MyBrainHurts at this ISP to reach me
Jul 23 '05 #22

P: n/a
Arthur Shapiro wrote:

<--snip-->
I just tried to diddle the code so that the "empty" squares that round out the
start and the end of the month in my calendar table would be automatically
colored. I made the previously discussed code an "else" block, using the
following code for the "if" block:

if (td[i].innerText=="")
{ td[i].bgColor = '#c63800'; }

Works like a champ in IE, but once again it does absolutely zilch in Mozilla.
I just don't yet have a feel for the necessary technique / discipline in
dealing with an issue like this


It works in IE but not Mozilla because .innerText is IE only code.

Start with your page in Mozilla, debug it there. Tools>Web
Development>Javascript Console. Once you have it working in Mozilla,
then and only then, test it in IE. You will soon find that it makes
debugging a lot simpler.

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq
Jul 23 '05 #23

P: n/a
Arthur Shapiro wrote:
OK, fair enough - as it had only been a couple of days I was working under the
assumption that it was a "current" topic.
I'll work under the assumption you are still reading this
thread...

Take a look at the minimal test case:

http://www.ocrebels.com/javascripttest.htm

This is one row of an html table-based calendar, with javascript courtesy of a
very helpful participant in this forum. The script is intended to change the
bgcolor of cells representing dates prior to today's date.

It does, in Internet Explorer.

It doesn't in Mozilla or Firefox. About the only obvious curiosity is that
the Mozilla javascript console reports "td has no properties" - which is
certainly true.

So the apparent question is: "is there something I need to know about
Javascript as implemented for Mozilla/Firefox, so I can achieve the same
functionality as seems to occur with IE?"


More like you need to learn the W3C DOM and the elements
interface. The problem with Microsoft is that they don't often
(ever?) tell you when they are extending the interface, so if you
just use their documentation and develop in IE, you will almost
certainly develop incompatible code.

Develop with Firefox/Mozilla/Netscape and test in IE and all the
others and you will have fewer issues to fix.

You could use the getElementsByTagName, but if you want a
"cleaner" fix, here's my suggestion:

Put your date cells into a tbody element. This is actually
required by the HTML spec, but because almost no one does it,
browsers insert it automatically where they think is appropriate.
So by using it, you are creating "better" HTML.

Now use getElementById on the tbody id, not the table id.
Incidentally, you should test for gEBI and add a method for
document.all if you think some of your visitors may be using an
old version IE (pre 5.5 I think).

Once you have the tbody, use the rows collection, then go through
the child nodes. Test for TDs and get the text from them and do
your stuff.

Lastly, 'bgcolor' is depreciated, use style="background-color: "
(since you are using style on the table anyway). The related DOM
attribute is accessed using 'camelCase' - style.backgroundColor.

Some sample code below. I have added a row and a thead to better
show how it all works. There are many other methods of getting
the cells and changing the contents, this way is OK but it is
unnecessarily dependent on the HTML structure of the cells (i.e.
that the cell firstChild is text and only a digit).

Another method is to dynamically create the calendar and set the
background color to the right value depending on the date
inserted into the cell when you create it. It takes fewer lines
of code overall but makes the page utterly dependent on
JavaScript. Of course, you could do it on the server and remove
client-side dependencies altogether.

Happy New Year! :-)

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><title>JavaScript Test Page</title>
<meta http-equiv="Content-Type" content="text/html;
charset=windows-1252">
</head>
<body>

<TABLE BORDER="5" WIDTH="100%"
style="FONT-FAMILY:Verdana; FONT-SIZE:10px;
background-color: #ffccc5;">
<thead>
<tr><td colspan="4">The header row</td></tr>
</thead>
<tbody id="calendar">
<TR ALIGN="LEFT" VALIGN="TOP">
<TD>0<br><BR>test</TD>
<TD>1<BR><BR>test</TD>
<TD>2<BR><br>test<BR></TD>
<TD>3<br><BR>test<BR></TD>
</tr><tr>
<TD>4<br><br>test<BR></TD>
<TD>5<BR><br>test<br></TD>
<TD>6<BR><br>test<br></TD>
<TD>&nbsp;</TD>
</TR>
</TABLE>

<script type="text/javascript">
var now = new Date().getDate(),
rows = document.getElementById('calendar').rows;
for (var i=0, rl=rows.length; i<rl; i++) {
var cells = rows[i].childNodes;
for (j=0, cl=cells.length; j<cl; j++) {
if (cells[j].nodeName == 'TD'
&& cells[j].firstChild.nodeValue != ''
&& cells[j].firstChild.nodeValue < now) {
cells[j].style.backgroundColor = '#c63800';
}
}
}
</script>
</html>
</body>

--
Rob
Jul 23 '05 #24

P: n/a
Thanks, both Randy and Rob. I'll be pondering your suggestions this evening,
not being much of a New Year celebrant. IE only, eh?! How was I supposed to
know that?

I think by the time I get this silly calendar behaving the way I want, I'll
know a lot more than when I started this thread.

The Java Console doesn't seem to do much for me but pop up an error once in a
while; am I missing something obvious that sets it as some sort of
trace/debugging engine?

Art


Art
Temporary usercode - to be deleted when spam starts. Use MyBrainHurts at this ISP to reach me
Jul 23 '05 #25

P: n/a
On Sat, 01 Jan 2005 01:35:50 GMT, Arthur Shapiro wrote:
The Java Console doesn't seem to do much for me but pop up an error once in a
while; am I missing something obvious that sets it as some sort of
trace/debugging engine?


The 'Java Console' usually monitors the Java Virtual Machine,
which runs Java (Applets) rather than Javascript, which is a
different language.

How to get the Javascript output would depend on the browser,
in UA's with the Mozilla engine and Opera, Javascript has a
separate console usually in the same menu as the Java Console.

AFAIR, IE displays an icon in the lower left to allow you to
open the JS console, but it's output is rather confounding, and
I understand there are much better plug-ins available for debugging
JS in IE.

OTOH, if you write your JS primarily testing in Moz./Opera, the
problems you experience with the script in IE should be minimal.

HTH

--
Andrew Thompson
http://www.PhySci.org/codes/ Web & IT Help
http://www.PhySci.org/ Open-source software suite
http://www.1point1C.org/ Science & Technology
http://www.LensEscapes.com/ Images that escape the mundane
Jul 23 '05 #26

P: n/a
In article <41***********************@per-qv1-newsreader-01.iinet.net.au>, RobG <rg***@iinet.net.auau> wrote:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><title>JavaScript Test Page</title>
<meta http-equiv="Content-Type" content="text/html;
charset=windows-1252">
</head>
<body>

<TABLE BORDER="5" WIDTH="100%"
style="FONT-FAMILY:Verdana; FONT-SIZE:10px;
background-color: #ffccc5;">
<thead>
<tr><td colspan="4">The header row</td></tr>
</thead>
<tbody id="calendar">
<TR ALIGN="LEFT" VALIGN="TOP">
<TD>0<br><BR>test</TD>
<TD>1<BR><BR>test</TD>
<TD>2<BR><br>test<BR></TD>
<TD>3<br><BR>test<BR></TD>
</tr><tr>
<TD>4<br><br>test<BR></TD>
<TD>5<BR><br>test<br></TD>
<TD>6<BR><br>test<br></TD>
<TD>&nbsp;</TD>
</TR>
</TABLE>

<script type="text/javascript">
var now = new Date().getDate(),
rows = document.getElementById('calendar').rows;
for (var i=0, rl=rows.length; i<rl; i++) {
var cells = rows[i].childNodes;
for (j=0, cl=cells.length; j<cl; j++) {
if (cells[j].nodeName == 'TD'
&& cells[j].firstChild.nodeValue != ''
&& cells[j].firstChild.nodeValue < now) {
cells[j].style.backgroundColor = '#c63800';
}
}
}
</script>
</html>
</body>

OK, I've spent some time looking at this example, which sure enough works in
both browsers.

My initial curiosity was why it correctly marked the "empty" cell with the
darker background color. Apparently the firstChild value for that cell of
"null" is numerically lower than the integer value of "now", and that makes
things work. Is that considered a "kosher" programming technique?

I then tried making the empty cell simply <td></td> and javascript failed on
an "object required" error. It's not a big deal to me to always have a space
or a <br> in the cell, but I'm curious what Javascript technique we might
typically use to isolate totally empty elements. That was why I had tried the
innerText construct before being told it was IE only.

Neglecting the reality that I'm trying to solve a real problem in the
organization's web site, this is all technically fascinating. I'm
appreciative of folks' patience.

Art
Temporary usercode - to be deleted when spam starts. Use MyBrainHurts at this ISP to reach me
Jul 23 '05 #27

P: n/a
In article <yGnBd.67836$QR1.4215@fed1read04>, Arthur Shapiro (arthur-
te****@cox.net) dropped a +5 bundle of words...
In article <41***********************@per-qv1-newsreader-01.iinet.net.au>, RobG <rg***@iinet.net.auau> wrote:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><title>JavaScript Test Page</title>
<meta http-equiv="Content-Type" content="text/html;
charset=windows-1252">
</head>
<body>

<TABLE BORDER="5" WIDTH="100%"
style="FONT-FAMILY:Verdana; FONT-SIZE:10px;
background-color: #ffccc5;">
<thead>
<tr><td colspan="4">The header row</td></tr>
</thead>
<tbody id="calendar">
<TR ALIGN="LEFT" VALIGN="TOP">
<TD>0<br><BR>test</TD>
<TD>1<BR><BR>test</TD>
<TD>2<BR><br>test<BR></TD>
<TD>3<br><BR>test<BR></TD>
</tr><tr>
<TD>4<br><br>test<BR></TD>
<TD>5<BR><br>test<br></TD>
<TD>6<BR><br>test<br></TD>
<TD>&nbsp;</TD>
</TR>
</TABLE>

<script type="text/javascript">
var now = new Date().getDate(),
rows = document.getElementById('calendar').rows;
for (var i=0, rl=rows.length; i<rl; i++) {
var cells = rows[i].childNodes;
for (j=0, cl=cells.length; j<cl; j++) {
if (cells[j].nodeName == 'TD'
&& cells[j].firstChild.nodeValue != ''
&& cells[j].firstChild.nodeValue < now) {
cells[j].style.backgroundColor = '#c63800';
}
}
}
</script>
</html>
</body>

OK, I've spent some time looking at this example, which sure enough works in
both browsers.

My initial curiosity was why it correctly marked the "empty" cell with the
darker background color. Apparently the firstChild value for that cell of
"null" is numerically lower than the integer value of "now", and that makes
things work. Is that considered a "kosher" programming technique?

I then tried making the empty cell simply <td></td> and javascript failed on
an "object required" error. It's not a big deal to me to always have a space
or a <br> in the cell, but I'm curious what Javascript technique we might
typically use to isolate totally empty elements.


Try this.

<td>&nbsp;</td>

Now your cell isn't empty but nothing shows. (It has a non-breaking
space in it)

--
Starshine Moonbeam
mhm31x9 Smeeter#29 WSD#30
sTaRShInE_mOOnBeAm aT HoTmAil dOt CoM



Jul 23 '05 #28

P: n/a
Arthur Shapiro wrote:
[...]
My initial curiosity was why it correctly marked the "empty" cell with the
darker background color. Apparently the firstChild value for that cell of
"null" is numerically lower than the integer value of "now", and that makes
things work. Is that considered a "kosher" programming technique?
It's not "null", it's a non-breaking space, which conveniently
evaluates as less than 1 (today for me being 1 Jan 2005). If you
put nearly any other character in there, it will be bigger than 1
and hence get the default colour. Even more conveniently, the
non-breaking space makes the geko-based browsers display the
'empty' cell. A normal plain space is removed - I suggest you
download Firefox to see what I mean.

I then tried making the empty cell simply <td></td> and javascript failed on
an "object required" error.
Yes, because there is no firstChild for the <TD> node. That can
be overcome, but then as previously mentioned, geko browsers
won't show the (now totally) empty cell even though IE does.

Incidentally, I don't think the HTML spec says what to do with
empty cells, so neither IE or Geko is "correct" here, but I think
IE's approach is more logical.
It's not a big deal to me to always have a space
or a <br> in the cell, but I'm curious what Javascript technique we might
typically use to isolate totally empty elements. That was why I had tried the
innerText construct before being told it was IE only.
Go the other way. Set the default colour, evaluate the value of
the firstChild as an int, then change it if it's equal to or
larger than today. But make the default reasonable so that
browsers without JS or not enabled can still use the site.

e.g.
...
<TABLE BORDER="5" WIDTH="100%" style="FONT-FAMILY:Verdana;
FONT-SIZE:10px; background-color: #aaaaaa;">
...

if (cells[j].nodeName == 'TD'
&& cells[j].firstChild.nodeValue != ''
&& +cells[j].firstChild.nodeValue >= now) {
cells[j].style.backgroundColor = '#ddddee';
}
...

Now your empty cells can be totally empty and will be OK in IE
and the Geko browsers.

The background-color can be set on the tbody, not the table, if
you want. It is also generally frowned upon to set font sizes in
px, use % or similar then set other sizes (cell widths, etc.) to
'em' and all will scale if visitors are using bigger or smaller
base fonts.
Neglecting the reality that I'm trying to solve a real problem in the
organization's web site, this is all technically fascinating. I'm
appreciative of folks' patience.


Ah, but that's the allure of web development!

--
Rob
Jul 23 '05 #29

P: n/a
RobG wrote:
[...]
if (cells[j].nodeName == 'TD'
&& cells[j].firstChild.nodeValue != ''
&& +cells[j].firstChild.nodeValue >= now) {
cells[j].style.backgroundColor = '#ddddee';
}
...

Now your empty cells can be totally empty and will be OK in IE
and the Geko browsers.


Ooops, I fibbed. I copied the wrong code, use:

for (j=0, cl=cells.length; j<cl; j++) {
if (cells[j].nodeName == 'TD'
&& cells[j].firstChild
&& cells[j].firstChild.nodeValue != ''
&& +cells[j].firstChild.nodeValue >= now) {
cells[j].style.backgroundColor = '#ddddff';
}
}

There is an extra test to see if firstChild exists at all so it
won't error if it doesn't (totally empty cell).

--
Rob
Jul 23 '05 #30

P: n/a
JRS: In article <j1mBd.67829$QR1.52379@fed1read04>, dated Sat, 1 Jan
2005 00:20:31, seen in news:comp.lang.javascript, Arthur Shapiro
<ar***********@cox.net> posted :
In article <RL**************@merlyn.demon.co.uk>, Dr John Stockton
<sp**@merlyn.demon.co.uk> wrote:
With that experience, you may well recall punched cards and the daily
test run.

Yep! (not to mention paper tape).

At the risk of overextending my welcome, your very comprehensive response
about code development doesn't seem to address one concern that I suspect
isn't unique to my own situation: how does one address behavioral differences
among browsers? The previous discussion of my personal calendar script got
into this, where something simply didn't work in Foxfire although it worked
fine in IE. Ivo gave a different approach that worked, and I happily used it,
but I don't know how I would have attacked the problem myself.

Well, the best answer is probably the trivial one of using only what you
know to work in "all" systems.
As far as I can see, there would be no problem in writing HTML to show
any one view of the calendar, as a Table; and that code would be fairly
repetitive.

FAQ 4.15 indicates how javascript can replace the contents of an
existing DIV (note : or other element), in any reasonable browser -
IIRC, that excludes mainly Netscape 4.

So you could compute the whole Table as a string to be rewritten to a
DIV every time the contents need to change - that uses more CPU cycles,
but plenty are available.

My <URL:http://www.merlyn.demon.co.uk/holidays.htm> works that way, and
AFAIK works in all browsers better than NS4 (RSVP if any US/CA, or
other, holidays are wrong).
Otherwise, when you find a feature that, as you have it, does not work
in some systems, see if you can isolate the use of that feature into a
single small parameterised function called whenever required, and then
generalise that function using feature detection (FAQ 4.26, FAQ Notes).

<FAQENTRY> 4.37 refers to "featuresting" </FAQENTRY>

--
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 #31

P: n/a
In article <YQ**************@merlyn.demon.co.uk>, Dr John Stockton <sp**@merlyn.demon.co.uk> wrote:

Well, the best answer is probably the trivial one of using only what you
know to work in "all" systems.
At this point, I don't have enough experience to know what works in all
systems!
FAQ 4.15 indicates how javascript can replace the contents of an
existing DIV (note : or other element), in any reasonable browser -
IIRC, that excludes mainly Netscape 4.
Interesting. The site is known to not render at all in Netscape 4, due to the
Javascript that positions all the page elements, so that's not an issue.
So you could compute the whole Table as a string to be rewritten to a
DIV every time the contents need to change - that uses more CPU cycles,
but plenty are available.


I'm *very* happy with the way things look right now, and don't see the need to
create it "on the fly", but I'll study that area of the FAQ for potential
future use. I will soon make the change that Rob suggested yesterday - I was
rather stunned to see that one could use the construct "cells[j].firstChild"
as a Boolean to establish whether or not the object even exists, thus allowing
a totally empty cell rather than having to insert a <br> or nonbreaking space.
That just seemed intuivitevely non-obvious; I'd expect it (validity checking)
to be some sort of method.

Anyway, everyone's been of great help here, and the calendar works like a
champ. I even found a member with a Mac, who reported it functioned as
expected. If any of you are bicyclists, and are visiting southern
California, we'd be honored to have you ride with us; you can see the
nuclear calendar partway down the page at http://www.ocrebels.com/rides.htm.

Art
Temporary usercode - to be deleted when spam starts. Use MyBrainHurts at this ISP to reach me
Jul 23 '05 #32

This discussion thread is closed

Replies have been disabled for this discussion.