.keypress on a DIV tag?

15,573

Yes: you need to add a tabindex attribute to the <div> to allow it to receive the focus.

<div id="idtext" tabindex="1"></div>

Also, the property you want for the character code of the text entered in a keypress event is which, not keyCode.

Finally, the HTML comment tags inside the <script> element are unnecessary in all modern browsers.

Share:
15,573
xRobot
Author by

xRobot

Updated on July 22, 2022

Comments

  • xRobot
    xRobot almost 2 years

    Is there a way to get work .keypress on a div element like this?:

    <html>
    <body>
    
    <script type="text/javascript">
    <!--
    
    $('#idtext').keypress(function(event) {
      var keyCode = event.keyCode;
      $('#idtext').text(function(i, text) {
    
       return text + String.fromCharCode(keyCode); 
    
      });
    
    });
    
    // -->
    </script>
    
    <div id="idtext"></div>
    
    </body>
    </html>
    
  • Tim Down
    Tim Down over 13 years
    The example is way too complicated to say that it's my suggestion that's not working. Simplified: jsbin.com/aqiza/7
  • jcubic
    jcubic over 13 years
    @xRobot you have mistake change $('#cmd span'); to $('#cmd div#mytext'); see jsbin.com/aqiza/13
  • SasQ
    SasQ over 12 years
    Many thanks for the tabindex trick. I'd never figure it out.