Jump to content
prateek88

change color of each <td> onClick event

Recommended Posts

hello, I want to develop a script which could change the each and every <td> cell in a table when clicking.What i am considering to achieve this is by assigning each <td> an id and use it as a function parameter, so that in function i could change the color of that particular cell. Something like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>Untitled Document</title><script type="text/javascript">function changeColor(id){var cell = document.getElementById(id);cell.style.background = red;//cell.style.color = black;}</script></head> <body><table><tr><td id='cell' onclick="changeColor('cell')">a1</td></tr></table></body></html>

but since onclick would not work for the <td> so what else better way to perform this. If someone could suggest better alternative for achieving sucha a thing it would be very kind. Note: All this to start my online movie ticket booking self learning project, so please guide me to the appropriate directionThanks in advance

Share this post


Link to post
Share on other sites

1) you do not require id ref for each cell using 'this' refers to current element that click event was triggered on <tr><td onclick="changeColor(this)">a1</td></tr>2) now that you are refering to current element

function changeColor(elem)

3) when refering to background color you use style.backgroundColor=4) colour is define within quotes as in 'red', "red" or using hex '#FF0000', "#FF0000"

elem.style.backgroundColor = "red";

  • Like 1

Share this post


Link to post
Share on other sites

Many thanks, for the quick reply. It is working now. Is there any more efficient way to achieve this as i will be using too many rows and cells according to the seats.

Share this post


Link to post
Share on other sites

Use a css to provide a alternance color in your html page. exemple: <style> .colorChoise { background-color="#FFCC99";} .colorChoise: hover { background-color="#FF99CC";}</style><table> <tr> <td class='colorChoise'></td> </tr></table>

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...