-1

I am writing a program where users select their availability. I have a mouse over color, but I would like that color to be confirmed on click. The only problem with the below solution is that upon a second click the isn't reset. How do I get it to reset?

<td onclick="javascript:this.style.background = '#000000';">
j08691
  • 204,283
  • 31
  • 260
  • 272
  • possible duplicate of [Change an element's CSS class with JavaScript](http://stackoverflow.com/questions/195951/change-an-elements-css-class-with-javascript) – Etheryte Jun 13 '14 at 00:51
  • 1
    You need a conditional check to determine if a color is applied or not. Here's a fiddle (http://jsfiddle.net/mun8y/) that uses a ternary operator to check. However, it probably makes more sense to use a CSS class and just add/remove that (which specifies the styles needed). – Jack Jun 13 '14 at 01:16

1 Answers1

1

jsBin demo

var $table = document.getElementById('myTable'),
    $td = $table.getElementsByTagName('td');

function fnToggle(){
  var io = this.io ^= 1; // Toggler
  this.style.backgroundColor = io ? "#000" : "transparent" ;
}

// Assign click handler (toward fnToggle) to all our TD elements
for(var i=0; i<$td.length;) $td[i++].onclick = fnToggle;

Read more about the use of (?:) here
Read more about the use of ^= here (+ bonus reading)

Community
  • 1
  • 1
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313