user5220361 user5220361 - 7 months ago 18
HTML Question

an HTML element listens to one event and then listens to another

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. Thanks a lot.

Answer

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>

Comments