Search code examples
jqueryhtml-tabletabindextablecell

jQuery activate function when TD gets focus


I've made an editable table that works well when my user clicks a table cell. However, I need the same functionality when the user tabs to a table cell (no mouse click). Here's the relevant jQuery:

$('.cd_editable').on('click', 'td', function () { 
    //do stuff
});

This works great when the user clicks a table cell. Is there some way I can alter this line so that it fires when my user tabs there? All the editable TDs have tabindex numbers, so the tabbing is working.

Thanks for any help.


Solution

  • Use the focus event.

    $("table tbody").on("focus", "td", function () {
      console.log(this)
    })
    td {
      width: 50px;
      border: 1px dashed black;
    }
    
    td:focus {
      background-color: #CCC
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <table>
      <tbody>
        <tr>
          <td contenteditable="true"></td>
          <td contenteditable="true"></td>
          <td contenteditable="true"></td>
          <td contenteditable="true"></td>
        </tr>
        <tr>
          <td contenteditable="true"></td>
          <td contenteditable="true"></td>
          <td contenteditable="true"></td>
          <td contenteditable="true"></td>
        </tr>
      </tbody>
    </table>