1

I am trying to click on each cell on the table so that the selected cells I click on change the background color from white to gray. I am also trying to make it like a toggle so if I click on the cell again the background changes from gray to white, but it is not doing anything. I found a similar question, but the answer was advanced coding. I want to create a simpler code. I checked Firebug, but I do not see any errors. I would appreciate any suggestions. I am new to Javascript.

http://jsfiddle.net/RE006/nyzswnx2/1/

HTML5:

<table class="bingo">
    <tr>
        <td id="square0"></td>
        <td id="square1"></td>
        <td id="square2"></td>
    </tr>
    <tr>
        <td id="square3"></td>
        <td id="square4"></td>
        <td id="square5"></td>

    </tr>
    <tr>
        <td id="square6"></td>
        <td id="square7"></td>
        <td id="square8"></td>
    </tr>
</table>

JS:

var toggleHighlight = function () {
    document.td.style.backgroundColor = "#cecece;"
}

window.onload = function () {
   getElementsByTagName("td").onclick = toggleHighlight ();
} 

6 Answers 6

2

First of all: document.getElementsByTagName('td') returns a NodeList and not a single node, so you have to cycle on it to attach the event listener:

JS:

window.onload = function () {
    var tds = document.getElementsByTagName("td");
    for (var i = 0; i < tds.length; i++)
        tds[i].onclick = toggleHighlight;
}

Please note that in the row tds[i].onclick = toggleHighlight;, toggleHighlight doesn't have ( and ) because it is a reference to a function and not a call to a function.

If you want to do things the web dev way, you should use classes instead of setting the color explicitly, so you can have:

JS:

function toggleHighlight() {
    var td = this;
    if (td.className == 'highlight')
        td.className = '';
    else
        td.className = 'highlight';
}

CSS:

.highlight {
    background-color: #cecece;
}

You can see the working example here: http://jsfiddle.net/nyzswnx2/40/

Please note that in order to make window.onload work I selected No wrap - in <body> instead of onLoad in the top left dropdown.

1
  • By the way, if you're new to Javascript I strongly recommend to use jQuery instead of vanilla Javascript, the code would be much more concise: jsfiddle.net/nyzswnx2/50
    – Matita
    Jul 20, 2015 at 8:33
1

Note that

  • document.getElementsByTagName returns an array.
  • when you set onclick, you're going to need a function (function() {}), not the return value of that function (which is undefined in your example of onclick = toggleHighlight ();)

As per your JavaScript, you might want to try something like

var toggleHighlight = function (e) {
    var bg = e.target.style.backgroundColor;
    if (bg == 'red') {
        e.target.style.backgroundColor = '';
    } else {
        e.target.style.backgroundColor = 'red';   
    }
}

var prepareTable = function () {
    var cells = document.getElementsByTagName("td");
    for (var i = 0 ; i < cells.length ; i++) {
        cells[i].onclick = function(event) {
            toggleHighlight(event);
        }
    }
}

document.onload = prepareTable();

Fiddle: http://jsfiddle.net/nyzswnx2/47/

5
  • Just to confirm "e" is the parameter and "event" from toggle.Highlight(event) is the argument? Is event from: function(event) a parameter? Jul 22, 2015 at 20:11
  • If I understood you correctly, then yes. onclick is called with an event parameter, so we'll need to have a function that takes that parameter. We'll then pass that event to toggleHightlight. Thus, e equals event in this example.
    – jsruok
    Jul 23, 2015 at 6:37
  • So since I am passing names, they are parameters. I am not passing any values so therefore I am not passing any arguments? Is this correct? w3schools.com/js/js_function_parameters.asp Jul 24, 2015 at 0:42
  • @user5117220: Please see stackoverflow.com/questions/427653/arguments-or-parameters
    – jsruok
    Jul 24, 2015 at 10:02
  • Thank you for the link, I really appreciate. Just to confirm: So in cells[i].onclick = function (event), event is the parameter and the .onclick event will call the toggleHighlight (event) then event becomes the argument. So I am passing two things to toggleHighlight: 1)clicking each cell (under prepareTable) and 2)turning the background from white to gray, and via versa. Jul 25, 2015 at 5:11
1

you can use jQuery it's more simple.

add a class css :

.gray {
background-color:#efefef;
 }

and change your code js with :

$(document).ready(function(){
  $('td').on('click',function(){
     $(this).toggleClass('gray');
  });
});

Demo :

http://jsfiddle.net/nyzswnx2/51/

0
getElementsByTagName("td").onclick = toggleHighlight (); 

First, this line is wrong, since getElementsByTagName() returns a list one is in need for a loop.

var tL = getElementsByTagName("td"); 
for(var i=0, j=tL.length; i<j; i++) tL[i].onclick = function(){this.style.backgroundColor = "#cecece"}

There is another possibility. Instead of defining an onclick() event for each cell in the table one could use onclick() event on the table and later on use the function document.elementFromPoint() to get the td. Yet the way used in the post (onclick() event on td) is pretty much standard.

To toggle the colors one needs to check whether colors are set yet or not (cecece in this case).

Example

<html>
    <head>
        <script>
            function Init(){
                document.querySelector('table').onclick = function(event){colorCell(event)}
            }

            function colorCell(event){
                var tE = document.elementFromPoint(event.clientX, event.clientY);
                if (tE.tagName === 'TD') tE.style.backgroundColor = (tE.style.backgroundColor === '') ? '#cecece' : ''
            }
        </script>
    </head>

    <body onload = 'Init()'>
        <table>
            <tr>
                <td>0.0</td>
                <td>0.1</td>
                <td>0.2</td>
            </tr>
            <tr>
                <td>1.0</td>
                <td>1.1</td>
                <td>1.2</td>
            </tr>
            <tr>
                <td>1.0</td>
                <td>1.1</td>
                <td>1.2</td>
            </tr>
        </table>
    </body>
</html>
1
  • I like the idea of having one event on the table instead of having one on each cell.
    – Lain
    Jul 20, 2015 at 8:38
0

First things first: your fiddle is already set to run the code on window.onload, so you have no need to repeat it. You can just write the code and it will automatically be executed upon load.

Now, for your question: you are attempting to assign an event listener to a Node Collection, while you really want to assign the event listener to each element of said collection. There are many ways to go about it, but you can safely do it like this:

var cells = document.getElementsByTagName('td');
for (var i = 0; i < cells.length; i++) {
    cells[i].addEventListener('click', toggleHighlight);
}

Please note two things:

  • I've used addEventListener instead of assigning the function to the onclick event. I encourage you to look up both ways of assigning events.
  • When assigning a function to an event or, generally speaking, referring to a function as a variable, you should NOT call the function, but simply refer to it by its name. In this example, I have passed the toggleHighlight function to the addEventListener function as its second parameter just by passing it the name of the function, not by calling it. If you were to call the function, the second parameter passed to the addEventListener function would be the return value of the toggleHighlight function, not a reference to the function itself. I encourage you to look up the differences between calling a function in JavaScript and passing a function as a reference.

Let's take a look to the toggleHighlight function now: this function is somehow special, because it responds to an event. As such, its first parameter is a reference to an event itself, and the function should therefore be written like this:

function toggleHighlight(event) {
    var cell = event.target;

    cell.style.backgroundColor = '#cecece';
}

See what I did there? I used the event object to get the target of the event, and I've set the style on the target itself. Every time a cell is clicked, the target of the event will refer to the cell on which the event was triggered.

Toggling the color requires your code to be stateful: it must somehow save the state of each cell, and use it to decide which color should be used for the background of the cell. Sure, we could use the color of the cell as a state, but that's not really acceptable so we're going to do some more work to get things working. The first thing you want to do is define the states that will be available, and store the initial state of each cell somewhere. We could updated our code like so:

const SQUARE_OFF = 0;
const SQUARE_ON  = 1;

var cells = document.getElementsByTagName('td');
var cellStates = {};

for (var i = 0; i < cells.length; i++) {
    cells[i].addEventListener('click', toggleHighlight);
    cellStates[cells[i].id] = SQUARE_OFF;
}

Let's look at what I did:

  • I declared two constants, one for each state, and assigned an arbitrary value to each of them. This is NOT the only way to do it, it's just one way;
  • I declared the cellStates variable as an empty object. We'll use this to store the states of each cell;
  • While looping through the cells, I used the current cell's id as the key to be used to store the cell's state within the cellStates object. Initially, all cells are going to be off. At the end of the loop, your cellStates will have a key for each cell with the cell's state stored within.

Now that we have saved the state, we want to update it every time we click on a cell, and change the color of the cell accordingly. Let's update our toggleHighlight function:

function toggleHighlight(event) {
    var cell = event.target;
    var cellState = (cellStates[cell.id] === SQUARE_OFF) ? SQUARE_ON : SQUARE_OFF;

    cellStates[cell.id] = cellState;

    cell.style.backgroundColor = (cellState === SQUARE_OFF) ? '#fff' : '#cecece';
}    

And, just like that, you can now toggle the color of each cell upon clicking. I encourage you to experiment and understand what's going on here very carefully before moving on to other topics. Have fun and happy learning!

Complete fiddle: http://jsfiddle.net/nyzswnx2/29/

2
  • Seeing the amount (and the type) of your questions I think your are trying to punch way above your weight here. I strongly recommend that you go back to the drawing board and try to start with something simpler in order not to get overwhelmed by all these concepts. Have you tried codecademy.com? Jul 21, 2015 at 7:51
  • You are right this is way above my head juan. I forgot about codeacademy.com, I will take a look at it. Do you suggest lynda.com too? I really appreciate you taking the time to write that long code and explain it to me. I am currently reading Javascript and Jquery. Jul 22, 2015 at 4:31
0

I like to delegate

Vanilla JS

window.addEventListener('load', function(e) {
  document.getElementById('tb').addEventListener('click', function(e) {
    const tgt = e.target.closest('td');
    if (tgt) tgt.classList.toggle('selected')
  })
})
table,
th,
td {
  border: 1px solid #000;
  border-collapse: collapse;
  font-size: 1.0rem;
  margin: 25px auto 0px auto;
  text-align: center;
}

th,
td {
  padding: 5px 10px;
}


/* bingo table */


.bingo td {
  color: #000;
  padding: 20px;
}

.bingo .selected {
  background-color: red;
}
<table class="bingo">
  <tbody id="tb">
    <tr>
      <td id="square0"></td>
      <td id="square1"></td>
      <td id="square2"></td>
    </tr>
    <tr>
      <td id="square3"></td>
      <td id="square4"></td>
      <td id="square5"></td>
    </tr>
    <tr>
      <td id="square6"></td>
      <td id="square7"></td>
      <td id="square8"></td>
    </tr>
    <tbody>
</table>

jQuery

$(function() {
  $('#tb tbody').on('click', 'td',  function(e) {
    $(this).toggleClass('selected')
  })
})
table,
th,
td {
  border: 1px solid #000;
  border-collapse: collapse;
  font-size: 1.0rem;
  margin: 25px auto 0px auto;
  text-align: center;
}

th,
td {
  padding: 5px 10px;
}


/* bingo table */


.bingo td {
  color: #000;
  padding: 20px;
}

.bingo .selected {
  background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<table class="bingo" id="tb">
  <tbody>
    <tr>
      <td id="square0"></td>
      <td id="square1"></td>
      <td id="square2"></td>
    </tr>
    <tr>
      <td id="square3"></td>
      <td id="square4"></td>
      <td id="square5"></td>
    </tr>
    <tr>
      <td id="square6"></td>
      <td id="square7"></td>
      <td id="square8"></td>
    </tr>
    <tbody>
</table>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.