views:

48

answers:

2

i want to focus an inputfield whenever i press a key.

so i use:

 $('body').live('keyup', function() {
      alert('testing');
 });

but it doesnt work.

is it wrong with my selector?

UPDATE:

here is my code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml"&gt;
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <title>TODO supply a title</title>
        <script type="text/javascript" src="../system/media/js/jquery/jquery.js"></script>
        <script type="text/javascript">

            $(document).ready(function() {
                $('body').live('keyup', function() {
                    alert('testing');
                });

            });

        </script>
    </head>
    <body>
        <p>
            TODO write content
        </p>
    </body>
</html>

and it doesnt work when i click on the 'TODO write content' and then press something. it works when i replace keyup with mouseover. then whenever i have the mouse over the 'TODO write content' it will alert me.

A: 

It does not work because your page does not have focus.. you need to click on the page first and it will work..

alternatively you could forcibly set the focus to an input element and thus bring focus to the page..

$(function(){ $('input_selector_here').focus(); });
Gaby
i have clicked on the page so it is focused before i type anything...but still doesnt work..i will make another try with another page to see if its something wrong with my current page
weng
+1  A: 

Try using $("html") or $("*") instead of $("body"). In order for the keyUp event on body to fire, the body node or one of its children must be focused. You can accomplish this in your example by adding a text input and focusing the mouse to that input. What you really want is to capture any key press, so $("html") should work.

Edit: I think your example might work, but in any case, to run the logic conditionally you might try...

if ($(document.body).is(".focusOnKeypress"))
   $("html").live(...)

Or, I think this will also work ...

$("body:not(.noFocusOnKeypress)").parent("html").live(...)
Bryan Matthews
thanks it worked. how do i select the whole page but not some specific class. tried $('html:not(.noFocusOnKeypress)') but it didnt work
weng
Response in the answer...
Bryan Matthews