user5220361
user5220361

Reputation: 21

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?

Upvotes: 1

Views: 56

Answers (2)

iplus26
iplus26

Reputation: 2647

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

Upvotes: 1

SEUH
SEUH

Reputation: 324

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>

Upvotes: 1

Related Questions