1

What I'm trying to do is that let one table cell element listens to one onclick() event, when this event evoked, do something and then add another keyboard event listener to this table cell element, but it does not seem to work, even though the new event listener is added.

I have a table of 10 x 10 created by html tags, and each of them assigned an id from 0 to 99.

Here is my code:

    for(i=0; i<100; i++){
        var cell = document.getElementById(i);
        cell.addEventListener("click", handleClick);
    }

    function handleClick(e){
        var cell = e.target;
        console.log(cell);
        cell.addEventListener("keyup", handleInput);
        console.log(true);

        cell.removeEventListener("click", handleClick);
        console.log(true);                       
    }

    function handleInput(e){
        var key = e.keyCode;
        var i = e.target.id;
        console.log(key);
        document.getElementById(i).innerHTML = key;
        }

The handleInput() function is not called when I press down a key on a cell, besides, the console showed 'true' twice after a cell clicked.

Can anyone tell me is there any problem with this? And how to fix it to achieve my goals?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • What information is your log shown? Till where is your code reaching? – Cristiano Mendonça Apr 30 '16 at 15:05
  • the handleInput() function is not called when i press down a key on a cell, besides, the console showed 'true' twice, means the new keyboard event listener was added successfully. thanks! – user5220361 Apr 30 '16 at 15:08

2 Answers2

1

Does work as is.

for(var i=0; i<100; i++){
  var cell = document.getElementById(i);
  cell.addEventListener("click", handleClick);
  console.log("test")
}

function handleClick(e){
  var cell = e.target;
  console.log(cell);
  cell.addEventListener("keyup", handleInput);
  console.log(true);

  cell.removeEventListener("click", handleClick);
  console.log(true);                       
}

function handleInput(e){
  var key = e.keyCode;
  var i = e.target.id;
  console.log(key);
  document.getElementById(i).innerHTML = key;
  document.getElementById("output").innerHTML = key;
}
<html>
  <table>
    <td><input id="0"></td>
  </table>
  <div id="output"></div>
</html>
SEUH
  • 314
  • 3
  • 15
  • Thanks a lot! It seems to have resolve my question. I think what probably went wrong is that i let a table cell HTML tag listen to a keyboard event. – user5220361 Apr 30 '16 at 15:24
1

The problem is you attach keyboard event listeners to static html elements. You can add tabindex to the td element like below:

<td tabindex="0">something<td>

Check out this question.

Reference - SCR29: Adding keyboard-accessible actions to static HTML elements

Community
  • 1
  • 1
iplus26
  • 2,518
  • 15
  • 26