3

Can any one tell me how to capture key events in div tag??

I wrote this code but it is not working?

<div id="SDiv" style="background-color: White; " onkeypress="kypress()">
     <asp:Label ID="LblSaveAndMoveNext" runat="server" Visible="False" Text="Save"></asp:Label>
</div>

<script type="text/javascript"> 
    function kypress() { EnableButtons(true);}
</script>
meo
  • 30,872
  • 17
  • 87
  • 123
Lakki
  • 65
  • 1
  • 6
  • div tag is not such tag which you can set focus to. – Behnam Esmaili Nov 23 '12 at 08:36
  • you must set focus to the div first.check this link for more info [1]: http://stackoverflow.com/questions/3149362/capturing-key-press-event-in-div. – Behnam Esmaili Nov 23 '12 at 08:41
  • Then how to achieve .In my page i don't have form tag.My requirement is when I press any key in the page i should call kypress() function. – Lakki Nov 23 '12 at 08:42

4 Answers4

1

You must have a focus in order to trigger the keypress event.

Or you could apply the keypress on the document object.

Using jQuery:

$(document).keypress(function(){
     /*do something*/
});
Behnam Esmaili
  • 5,835
  • 6
  • 32
  • 63
Jonathan de M.
  • 9,721
  • 8
  • 47
  • 72
1

Only elements that can receive focus, such as inputs and other form-related elements, will fire key events. To force a <div> element to be able to receive focus, you can either make it contenteditable, which is probably not what you want, or add a tabindex attribute. Using a value of 0 will place the element at the default position in the tab order.

<div id="SDiv" tabindex="0" style="background-color: White;"
     onkeypress="kypress()">
    ...
</div>
Tim Down
  • 318,141
  • 75
  • 454
  • 536
0

You can overcome it by using a contenteditable div, like this. Make sure you return false to prevent the changes in html.

    <div  id="SDiv" contenteditable="true" 
    style="background-color: White; " tab-index="1" onkeydown="return keydown();">
       <asp:Label ID="LblSaveAndMoveNext" runat="server" Visible="False" Text="Save"></asp:Label>           
    </div>


    <script type="text/javascript">
        function keydown(){
            var keyCode = event.which;
            if(keyCode==13)
                document.write('You pressed Enter');
            //do your logic here
            return false;
        }
    </script>
Akhil Sekharan
  • 12,467
  • 7
  • 40
  • 57
0

Please refer to the thread "jQuery Event Keypress: Which key was pressed?" for the answer...

You need to set the tabindex attribute of the div as given below:

<div id="example" tabindex="1" />
Community
  • 1
  • 1
shintoZ
  • 311
  • 2
  • 12