changing td bgcolors on the fly

Discussion in 'Javascript' started by Holden Caulfield, Dec 13, 2003.

  1. Hi there,
    for IE 5+ I need to be able to change certain TD tags´ background
    colors, and can´t figure out how to do it...

    For instance, in a table with 25 cells, somewhere between 5 or 10 will
    need the bgcolor to change at the same time when a user clicks a
    button. Right now only one changes when I use something like this...

    document.getElementById(´cellchange´).style.backgroundColor = "FFFFFF"
    ** (Note, this is not the EXACT code, I am typing from memory... but
    it is SOMEthing like thw above...)

    where a few td cells have an "id=cellchange" in there tag. I need ALL
    of the ones with that ID to change!

    Is there a getElementByClass, for multiple similar elements?

    Thanks!

    Holden
    PS: The cells to change are set through ASP and are different for
    every user.
    PPS: It is an intranet app and ONLY HAS TO WORK WITH IE 5 and later!!
     
    Holden Caulfield, Dec 13, 2003
    #1
    1. Advertising

  2. Holden Caulfield wrote on 13 Dec 2003 at Sat, 13 Dec 2003 22:14:32
    GMT:

    > Hi there,
    > for IE 5+ I need to be able to change certain TD tags´
    > background colors, and can´t figure out how to do it...
    >
    > For instance, in a table with 25 cells, somewhere between 5 or
    > 10 will need the bgcolor to change at the same time when a user
    > clicks a button. Right now only one changes when I use
    > something like this...
    >
    > document.getElementById(´cellchange´).style.backgroundColor =
    > "FFFFFF" ** (Note, this is not the EXACT code, I am typing from
    > memory... but it is SOMEthing like thw above...)
    >
    > where a few td cells have an "id=cellchange" in there tag. I
    > need ALL of the ones with that ID to change!


    An ID /must/ be unique in a document. You /cannot/ give multiple
    elements the same ID.

    > Is there a getElementByClass, for multiple similar elements?


    You could assign the cells a common class name then use
    document.getElementsByTagName() to retrieve all table cells in the
    document. You can then loop through the collection returned and
    search for those elements that match that class ('cellchange',
    below):

    // Check that browser supports DOM method
    if (document.getElementsByTagName) {
    // Get table cells in document
    var cells = document.getElementsByTagName('td');
    var numCells = cells.length;

    // Loop through elements returned
    for (var i = 0; i < numCells; ++i) {
    // If cell should be changed (matching class)...
    if ('cellchange' == cells.className) {
    // ...alter the colour value
    cells.style.backgroundColor = '#FFFFFF';
    }
    }
    }

    I haven't tried this, but from the looks of the DHTML reference in
    Microsoft's MSDN Library, it should work. Just a reminder: colour
    (RGB) values must have a hash (#) symbol in front of them.

    Mike

    --
    Michael Winter
    d (replace ".invalid" with ".uk")
     
    Michael Winter, Dec 13, 2003
    #2
    1. Advertising

  3. Holden Caulfield

    Evertjan. Guest

    Holden Caulfield wrote on 13 dec 2003 in
    comp.lang.javascript:
    > PS: The cells to change are set through ASP and are
    > different for every user.
    > PPS: It is an intranet app and ONLY HAS TO WORK WITH IE 5
    > and later!!


    With serverside asp-vbs and clientside css classes you can
    set what class belongs to what <td>:

    <%
    if user="Holden" then c17="clGreen" else c17="clRed"
    if b=true then c18="clGreen" else c18="clRed"
    if c17="clRed" then c19="clGreen" else c19="clRed"
    if user<>"Holden" then c20="clGreen" else c20="clRed"
    if ... then c21="clGreen" else c21="clRed"
    %>
    <style>
    ..clGreen {color:green;background-color:black;}
    ..clRed {color:red;background-color:navy;}
    </style>

    <td class='<%=c17 %>'>.....
    <td class='<%=c18 %>'>.....
    <td class='<%=c19 %>'>.....
    <td class='<%=c20 %>'>.....
    <td class='<%=c21 %>'>.....

    with clientside js you can change the values of each class:

    <script>
    myRules = document.styleSheets[0].rules;
    // if the style declaration is the first one

    function changeClGreenBg(x) {
    myRules[0].style.backgroundColor = x;
    // first rule is clGreen
    }
    </script>

    <button onclick="changeClGreenBg('red')">
    black bgs to become red</button>

    Not tested! Believed to be good, perhaps debuging is in
    order.
    Only for IE, as NS wants cssRules, nor rules

    --
    Evertjan.
    The Netherlands.
    (Please change the x'es to dots in my emailaddress)
     
    Evertjan., Dec 13, 2003
    #3
  4. Holden Caulfield

    @SM Guest

    Holden Caulfield a ecrit :

    > Hi there,
    > for IE 5+ I need to be able to change certain TD tags´ background
    > colors, and can´t figure out how to do it...
    >
    > where a few td cells have an "id=cellchange" in there tag. I need ALL
    > of the ones with that ID to change!


    function chang(){
    D = document.getElementsByTagName('td');
    for(i=0;i<D.length;i++)
    if(D.id=='cellchange')
    D.style.background='red';
    }

    > Is there a getElementByClass, for multiple similar elements?


    no, I don't think so

    do a test with that :

    <html><script type="text/javascript">
    function d(e){
    f='document.'+e;
    e=eval('document.'+e);
    if(e) {c='green'; r='YES';} else {c='yellow'; r='NO';}
    t ='<tr><th>'+f+'</th><td bgcolor="'+c+'">'+r+'</td></tr>';
    return t;
    }
    t = '';
    A = new Array('getElementById','getElementByTagName',
    'getElementByTags','getElementByTagsName',
    'getElementByTagsNames','getElementsByTag',
    'getElementsByTagName','getElementsById','getElementByName',
    'getElementsByName','createElement','getElementByClass',
    'getElementByClassName','getElementsByClassName');
    T='<table>';
    for(i=0;i<A.length;i++)
    T += d(A);
    T+= '</table>';
    document.write(T);
    </script></html>

    > Thanks!
    >
    > Holden
    > PS: The cells to change are set through ASP and are different for
    > every user.


    and ?? is it important ?

    > PPS: It is an intranet app and ONLY HAS TO WORK WITH IE 5 and later!!


    that does on mine (Mac IE 5.0)

    variantes :
    ---- 1 ----
    function phpchang(){
    D = document.getElementsByTagName('td');
    for(i=0;i<D.length;i++)
    if(D.id=='cellchange')
    D.style.background='<? echo $color ?>';
    }

    ----- 2 -----
    function tdBac(color){
    D = document.getElementsByTagName('td');
    for(i=0;i<D.length;i++)
    if(D.id=='cellchange')
    D.style.background=color;
    }

    <a href="javascript:tdBac('yellow');"> Yellow </a>
    <a href="javascript:tdBac('#333');"> Grey </a>

    --
    **************************************************************
    Stéphane MORIAUX : mailto:
    Aide aux Pages Perso (images & couleurs, formulaire, CHP, JS)
    http://perso.wanadoo.fr/stephanePOINTmoriaux/internet/
    **************************************************************
     
    @SM, Dec 13, 2003
    #4
  5. @SM wrote on 13 Dec 2003 at Sat, 13 Dec 2003 23:57:55 GMT:

    > function chang(){
    > D = document.getElementsByTagName('td');
    > for(i=0;i<D.length;i++)
    > if(D.id=='cellchange')
    > D.style.background='red';
    > }


    Pretty much what I said, except that you're ignoring the fact that
    only /one/ instance of an ID can appear in a document. Even if IE
    allows it, it's still wrong and there's an alternative solution
    (mine). I haven't tested it, but it should work if Microsoft conform
    to their own documentation.

    Mike

    --
    Michael Winter
    (replace ".invalid" with ".uk")
     
    Michael Winter, Dec 14, 2003
    #5
  6. Mateusz wrote on 20 Dec 2003 at Sat, 20 Dec 2003 10:21:11 GMT:

    > function chang(table_id, bgc){
    > d = document.getElementsById(table_id.GetElementsByTagName('td');


    This is a syntax error:

    1) The document object doesn't have the method, getElementsById().
    2) The correct method, getElementById(), takes a single String
    argument that contains the ID of the element.
    3) The table object doesn't have the method, GetElementsByTagName().
    4) The correct method, getElementsByTagName(), returns a collection
    (in your code) of table cells which, as already mentioned, is not
    the correct type for getElementById().
    5) You have a mismatching bracket; no closing ')'.

    From a good practice point-of-view, you should declare 'd' above and
    'i' below using the var keyword (so they're in local scope). Finally,
    you should test that the methods called are available before using
    them.

    I expect that you meant to do:

    var d = table_id.getElementsByTagName('td');

    > for(i=0;i<d.length;i++) d.style.background=bgc;
    > }
    >
    > <table id="sth">...</table>
    >
    > <script type="text/javascript" language="javascript"> <!-- <![CDATA[


    There's no need to use the language attribute.

    > chang( "sth", "red");
    > // ]]> -->
    > </script>


    One last point, the OP wanted to change the background of specific
    cells, not the entire table. If your first line is used with my
    solution, it will produce a much more efficient method:

    // Changes the background colour of table cells
    //
    // table - the table object to be re-coloured
    // cellClass - a string with the class name that changeable cells
    // should have
    // colour - a string containing the new background colour of the
    // form '#rrggbb'
    //
    function changeCells( table, cellClass, colour ) {
    var cells = null;

    if (table.getElementsByTagName) {
    cells = table.getElementsByTagName('td');
    } else if (table.cells) {
    cells = table.cells;
    }

    if (cells) {
    var numCells = cells.length;

    for (var i = 0; i < numCells; ++i) {
    if (cellClass == cells.className) {
    cells.style.backgroundColor = colour;
    }
    }
    }
    }

    One thing I didn't get around to checking was if the style access
    above works on non-IE supporting browsers (NS and Mozilla, for
    example). I haven't figured out the DOM Level 2 Style Spec. yet, so if
    someone can provide an example, I'd be grateful.

    Mike

    --
    Michael Winter
    d (replace ".invalid" with ".uk")
     
    Michael Winter, Dec 20, 2003
    #6
  7. Michael Winter <> writes:

    > I expect that you meant to do:
    >
    > var d = table_id.getElementsByTagName('td');


    more likely
    var d = document.getElementById(table_id).getElementsByTagNam('td');
    The table_id is a string, not the table element node itself.


    > if (table.getElementsByTagName) {
    > cells = table.getElementsByTagName('td');
    > } else if (table.cells) {


    Which browser is this? The DOM allows "table.rows", where each row
    contains a "cells" property.

    For IE 4, you can use
    table.all.tags("td")

    > if (cellClass == cells.className) {
    > cells.style.backgroundColor = colour;


    > One thing I didn't get around to checking was if the style access
    > above works on non-IE supporting browsers (NS and Mozilla, for
    > example).


    It's absolutely correct.

    > I haven't figured out the DOM Level 2 Style Spec. yet, so if
    > someone can provide an example, I'd be grateful.


    elemNode.style.backgroundColor = "white"
    is a fine example of DOM 2 Style CSS.
    Browsers let element nodes implement the ElementCSSInlineStyle interface,
    so they have a "style" property that is a CSSStyleDeclaration. That
    again can be accessed using the interface of CSSStyleDeclaration, with
    normal object property access notation being equivalent to the "item"
    method.


    Good lcuk.
    /L
    --
    Lasse Reichstein Nielsen -
    DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
    'Faith without judgement merely degrades the spirit divine.'
     
    Lasse Reichstein Nielsen, Dec 20, 2003
    #7
  8. Lasse Reichstein Nielsen wrote on 20 Dec 2003 at Sat, 20 Dec 2003
    13:30:59 GMT:

    > Michael Winter <> writes:
    >
    >> I expect that you meant to do:
    >>
    >> var d = table_id.getElementsByTagName('td');

    >
    > more likely
    > var d =
    > document.getElementById(table_id).getElementsByTagNam('td');
    > The table_id is a string, not the table element node itself.


    Was it? Oops.

    >> if (table.getElementsByTagName) {
    >> cells = table.getElementsByTagName('td');
    >> } else if (table.cells) {

    >
    > Which browser is this? The DOM allows "table.rows", where each row
    > contains a "cells" property.


    table.cells is directly from Microsoft's DHTML reference (my
    newsreader might destroy this URL):

    http://msdn.microsoft.com/workshop/author/dhtml/reference/collections/
    cells.asp

    If 'object' in the first usage presented is a table object, all of the
    cells in the table are returned. It doesn't state when it was
    introduced.

    > For IE 4, you can use
    > table.all.tags("td")


    That might be a necessary replacement for the second branch.

    >> if (cellClass == cells.className) {
    >> cells.style.backgroundColor = colour;

    >
    >> One thing I didn't get around to checking was if the style access
    >> above works on non-IE supporting browsers (NS and Mozilla, for
    >> example).

    >
    > It's absolutely correct.


    Though I forgot to add a check to see if the style property was
    implemented.

    >> I haven't figured out the DOM Level 2 Style Spec. yet, so if
    >> someone can provide an example, I'd be grateful.

    >
    > elemNode.style.backgroundColor = "white"
    > is a fine example of DOM 2 Style CSS.
    > Browsers let element nodes implement the ElementCSSInlineStyle
    > interface, so they have a "style" property that is a
    > CSSStyleDeclaration. That again can be accessed using the
    > interface of CSSStyleDeclaration, with normal object property
    > access notation being equivalent to the "item" method.


    Thank you. As I've had no need to modify style properties, or in fact
    use any Level 2 DOM, I wasn't sure what the correct syntax was. I only
    knew that MS' DHTML supports it (from IE 4 onwards).

    Mike

    --
    Michael Winter
    d (replace ".invalid" with ".uk")
     
    Michael Winter, Dec 20, 2003
    #8
  9. Michael Winter <> writes:

    > table.cells is directly from Microsoft's DHTML reference (my
    > newsreader might destroy this URL):
    >
    > http://msdn.microsoft.com/workshop/author/dhtml/reference/collections/cells.asp


    I see. It is slightly misleading. They say the collection is defined in he
    W3C DOM level 1. That is partially correct, but W3C DOM 1 only puts it as
    a property of the HTMLTableRowElement, not on HTMLTableElement.

    > If 'object' in the first usage presented is a table object, all of the
    > cells in the table are returned. It doesn't state when it was
    > introduced.


    So that is non-W3C DOM behavior.

    /L
    --
    Lasse Reichstein Nielsen -
    DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
    'Faith without judgement merely degrades the spirit divine.'
     
    Lasse Reichstein Nielsen, Dec 20, 2003
    #9
  10. Mateusz wrote:

    > <script type="text/javascript" language="javascript"> <!-- <![CDATA[
    > [...]
    > // ]]> -->
    > </script>


    Using an XML parser the above should result in an `<script/>'.
    Using a tag soup parser it depends on how much tag soup it eats.


    PointedEars
     
    Thomas 'PointedEars' Lahn, Dec 20, 2003
    #10
  11. Just wanted to say thanks for the responses! Especially Mike
    Winters´, whose code worked perfectly!

    Thanks again!

    Holden
    PS: Sorry for the late reply, I am travelling in Latin America and
    connections are, er, erratic...
     
    Holden Caulfield, Dec 20, 2003
    #11
  12. Holden Caulfield

    Jim Ley Guest

    On Sat, 20 Dec 2003 23:53:08 +0100, Thomas 'PointedEars' Lahn
    <> wrote:

    >Mateusz wrote:
    >
    >> <script type="text/javascript" language="javascript"> <!-- <![CDATA[
    >> [...]
    >> // ]]> -->
    >> </script>

    >
    >Using an XML parser the above should result in an `<script/>'.


    Surely not! There's 2 whitespace nodes and a comment inside the
    script element... :)

    Jim.
    --
    comp.lang.javascript FAQ - http://jibbering.com/faq/
     
    Jim Ley, Dec 22, 2003
    #12
  13. Jim Ley wrote:

    > Thomas 'PointedEars' Lahn wrote:
    >> Mateusz wrote:
    >>> <script type="text/javascript" language="javascript"> <!-- <![CDATA[
    >>> [...]
    >>> // ]]> -->
    >>> </script>

    >>
    >> Using an XML parser the above should result in an `<script/>'.

    >
    > Surely not! There's 2 whitespace nodes


    True :)

    > and a comment inside the script element... :)


    I wrote: `should *result* in'. After parsing, the comment is no more
    since it is required for an XML parser to remove all comments *before*
    building the parse tree.


    PointedEars
     
    Thomas 'PointedEars' Lahn, Dec 22, 2003
    #13
  14. Holden Caulfield

    Jim Ley Guest

    On Mon, 22 Dec 2003 17:21:30 +0100, Thomas 'PointedEars' Lahn
    <> wrote:

    >Jim Ley wrote:
    >> and a comment inside the script element... :)

    >
    >I wrote: `should *result* in'. After parsing, the comment is no more
    >since it is required for an XML parser to remove all comments *before*
    >building the parse tree.


    I understood the removal of comments was optional, not required that
    they do that.

    Jim.
    --
    comp.lang.javascript FAQ - http://jibbering.com/faq/
     
    Jim Ley, Dec 23, 2003
    #14
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Ian

    Ideas for changing CSS on fly?

    Ian, Jun 19, 2004, in forum: ASP .Net
    Replies:
    1
    Views:
    391
    clintonG
    Jun 19, 2004
  2. Phil Winstanley [Microsoft MVP ASP.NET]

    Re: Ideas for changing CSS on fly?

    Phil Winstanley [Microsoft MVP ASP.NET], Jun 19, 2004, in forum: ASP .Net
    Replies:
    4
    Views:
    427
    clintonG
    Jun 20, 2004
  3. RCS
    Replies:
    1
    Views:
    325
    Peter Morris [Droopy eyes software]
    Mar 31, 2005
  4. RoDzZzZ

    why backgrounds and bgcolors not print?

    RoDzZzZ, Aug 12, 2003, in forum: Javascript
    Replies:
    1
    Views:
    125
    cwdjr
    Aug 13, 2003
  5. Brian

    Fly outmenu on the fly

    Brian, Apr 8, 2005, in forum: Javascript
    Replies:
    0
    Views:
    133
    Brian
    Apr 8, 2005
Loading...

Share This Page