Crash on the body?

I want to receive alerts when I press a key.

I tried:

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

But that doesn't work, maybe because of the 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"> <html xmlns="http://www.w3.org/1999/xhtml"> <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> 

It does not warn me when I press something, although it works when I replace keyup with mouseover and hover over TODO write content

Why doesn't it work?

+3
source share
5 answers

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

Change I think your example might work, but anyway for conditional logic you can try the following:

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

Or, I think this will also work:

 $("body:not(.noFocusOnKeypress)").parent("html").live(...); 
+6
source

Just listen to the window!

 $(window).keydown(function(event){ alert(event.keyCode); }); 
+4
source

I tried this code. This works fine.

 $('body').on('keyup', function() { alert('testing'); }); 
+2
source

This does not work because your page has no focus. You need to click on the page first and it will work.

alternatively, you can force the focus on the input element and thus shift the focus to the page.

 $(function(){ $('input_selector_here').focus(); }); 
0
source

Hope this helps.

 $(document.body).on('keyup', function (e) { alert('In'); }): 
0
source

Source: https://habr.com/ru/post/903820/


All Articles