Jump to content

Archived

This topic is now archived and is closed to further replies.

Henky

changing colors

Recommended Posts

ok, i have a simple table with 2 rows, and 3 columns.
i want that when i click on a one cell, it transforms that cell from white to yellow.
how can this be done ?

i belive it's not difficult for you people, but for me as a newbie... I've tried for 4 hours now and still can't figure it out. can anyone post the code  for me ?

Share this post


Link to post
Share on other sites
It certainly isn't php.  Javascript would be able to do it.

Moving your post to that forum.

Share this post


Link to post
Share on other sites
you can create buttons that can change the color of the cell but as for clicking on the cell itself i dont think thats possibe but i could be wrong.

Share this post


Link to post
Share on other sites
I have found what you are looking for. You can find it at http://www.pageresource.com/dhtml/jtut6.htm
but it is simple:
<TABLE width="200" border="1" cellspacing="0" cellpadding="0">
<TR>
<TD style="width:100%; background-color:lightblue"
onMouseover="this.style.backgroundColor='yellow';"
onMouseout="this.style.backgroundColor='lightblue';">
Watch me get scared!
</TD>
</TR>
</TABLE>

Share this post


Link to post
Share on other sites
here's a much more useable solution -- add this javascript to the top of your page, add the classes to your CSS, and you'll be good to go:

CSS:
[code]
td {
  background-color: #FFFFFF;
}

td.highlight {
  background-color: #FCFDD0;
}
[/code]

Javascript:
[code]
function tdClick() {
  var tdEls = document.getElementById("myTable").getElementsByTagName("TD");
  for (var i = 0; i < tdEls.length; i++) {
    tdEls[i].onclick = function() {
      this.className += " highlight";
    }
  }
}

window.onload = function() {
  tdClick();
}
[/code]

whatever the ID is of your table you want to react to this needs to be reflected in the JS line getElementByID().

good luck

one other thought... if you want it to switch back to white on the second click, update the function to this:
[code]
function tdClick() {
  var tdEls = document.getElementById("myTable").getElementsByTagName("TD");
  for (var i = 0; i < tdEls.length; i++) {
    tdEls[i].onclick = function() {
      if (/highlight/.test(this.className)) {
        this.className = this.className.replace(new RegExp(" ?highlight\\b"), "");
      } else {
        this.className += " highlight";
      }
    }
  }
}
[/code]

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.