-1

I want to change the color of an element onClick - however I already have an onCLick function attached to the HTML element already. here is my code

function changeColor(cell){
    for (var i=0;i<cell.length;i++){
        cell[i].classList.remove("active")}
        elem.classList.add("active");
    }

}

table>
      <tr>
        <td><input  type="button"class= "input" id="cell1" onclick="clickThis(this.id)"></input></td>
        <td><input  type="button"class= "input" id="cell2" onclick="clickThis(this.id)"></input></td>
        <td><input  type="button"class= "input" id="cell3" onclick="clickThis(this.id)"></input></td>
      </tr> 
      <tr> 
marcusps1
  • 35
  • 7

2 Answers2

0

You can have multiple function calls in your onclick attribute:

onclick="clickThis(this.id); changeColor(this);"

However it would be cleaner to wrap this into one:

onclick="cellClick(this);"

function cellClick(cell){
   clickThis(cell.id);
   changeColor(cell);
}

It would be even better if you abstracted this from your HTML and used event listeners.

Curtis
  • 101,612
  • 66
  • 270
  • 352
  • IMHO, the whole DOM0 `onclick` stuff should be actively avoided in answers here - it's _so_ 1990s. Using `addEventListener` is the only true answer. – Alnitak Jul 06 '15 at 08:34
0

It will be better to use addEventLister() instead of using inline handler....

But to work with inline handlers, you can

function clickThis(id) {
  snippet.log('clicked: ' + id)
};

function changeColor(cell) {
  var tr = cell.parentNode;
  for (var i = 0; i < tr.children.length; i++) {
    tr.children[i].classList.remove("active")
  }
  cell.classList.add("active");
}
.active {
  color: red;
  border: 1px solid green;
}
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>


<table>
  <tr>
    <td>
      <input type="button" class="input" id="cell1" onclick="clickThis(this.id); changeColor(this.parentNode)" />
    </td>
    <td>
      <input type="button" class="input" id="cell2" onclick="clickThis(this.id); changeColor(this.parentNode)" />
    </td>
    <td>
      <input type="button" class="input" id="cell3" onclick="clickThis(this.id); changeColor(this.parentNode)" />
    </td>
  </tr>
  <tr>
    <td>
      <input type="button" class="input" id="cell4" onclick="clickThis(this.id); changeColor(this.parentNode)" />
    </td>
    <td>
      <input type="button" class="input" id="cell5" onclick="clickThis(this.id); changeColor(this.parentNode)" />
    </td>
    <td>
      <input type="button" class="input" id="cell6" onclick="clickThis(this.id); changeColor(this.parentNode)" />
    </td>
  </tr>
</table>
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531