Search code examples
javascripthighlighthtml-table

How to highlight Table TD when clicked?


basically I have a table grid like the one below, just a lot bigger.

<table>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</table>

And iv used CSS to make then all squares which are 60px by 60px, they wont contain any data but I want to be able to click on the individual squares so that the background color changes and if I click again it goes back to the origional background color. But I want to be able to highlight as many squares as I want. I know it would be in JavaScript, but how would I do this?


Solution

  • try this:

    <table>
        <tr>
            <td>test 1</td>
            <td>test 2</td>
        </tr>
        <tr>
            <td>test 3</td>
            <td>test 4</td>
        </tr>
    </table>​
    

    and script

    window.onload = function(){
    
        var all = document.getElementsByTagName("td");
        for (var i=0;i<all.length;i++) {
            all[i].onclick = inputClickHandler;       
        }
    };
    
    function inputClickHandler(e){
        e = e||window.event;
        var tdElm = e.target||e.srcElement;
        if(tdElm.style.backgroundColor == 'rgb(255, 0, 0)'){
            tdElm.style.backgroundColor = '#fff';
        } else {
            tdElm.style.backgroundColor = '#f00';
        }
    }
    ​
    

    DEMO