I am trying to catch the "ctrl + f" event in Javascript.
Even though, any letter on my keyboard fires an event,
"ctrl" does not.
Could you help me, please?
Below, is the code I execute:
if (event.ctrlKey && event.key === 'f') {
event.preventDefault();
document.querySelector("#search").focus();
}
Use the 'onkeydown' event to capture the ctrl event.
<html>
<head>
<title>ctrlKey example</title>
<script type="text/javascript">
function checkKeyPress(e){
if (event.ctrlKey ) {
event.preventDefault();
alert(
"CTRL key pressed: " + e.ctrlKey + "\n"
);
}
}
</script>
</head>
<body onkeydown="checkKeyPress(event);">
<p>Press CTRL</p>
</body>
</html>
Related
I want to detect when the user pressed a key that's not the "enter" button.
For example: if the user pressed the "shift" key it will do something.
I have this code but it's not working:
$(document).keypress(function(e) {
var keycode = (e.keyCode ? e.keyCode : e.which);
if (keycode!= '13) {
//do somthing
}
});
KeyboardEvent.keyCode and KeyboardEvent.which are both deprecated (confusing, I know). Use KeyboardEvent.code like so:
$(document).keypress(function(e){
if(e.code !== "Enter"){
// Your code here
}
});
More information at MDN
Try
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
document.onkeydown = function(e) {
if (!e.shiftKey) {
alert("You have entered a key that was not shift");
}
};
});
</script>
</head>
<body>
Please try to enter a key.
</body>
</html>
Assume we have this code:
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type="text/javascript">
var p = 0;
function reset()
{
// some efforts
}
function code(e) {
e = e || window.event;
return(e.keyCode || e.which);
}
window.onload = function(){
document.onkeypress = function(e){
var key = code(e);
if(key == 38 || key == 40)
{}
else if(e.altKey)
{
alert('altkey pressed');
}
else
{
// Another THING!
}
};
};
</script>
</head>
<body style="padding:30px; font-size:30px;font-family: Courier;">
<span onclick="reset();" accesskey="r"></span>
</body>
</html>
It works great in Firefox but not in IE an Chrome.
When I change alt into shift it works on all browsers. but as you may notice, I wanted to use this for Shortcut key and I think this is a problem of Alt key in Chrome and IE (because both use Alt for accesskey attribute but Firefox uses Alt+Shift as mentoned here).
So guys what you suggest me to do ?
You can not detect alt button on chrome because it enables the window menu, so your page lose focus and the event "keypress" is not called. The event "keydown" on the other hand is called so you can use it with no problem.
I want to know when user press W with shift. I am not getting any logic for this. Kindly suggest.
<head>
<script type="text/javascript" src="jquery-1.8.3.js"></script>
<script type="text/javascript">
$(function() {
$('body').keydown(function(e) {
var key= e.keyCode;
});
});
</script>
</head>
<body>
<div class="test">test</div>
</body>
W has key code 87, while jQuery event object has .shiftKey flag:
if (e.which === 87 && e.shiftKey) { ... }
DEMO: http://jsfiddle.net/etgAB/
You should have true in the event object at e.shiftKey, besides of the keycode of W (87)
Learn more about the jQuery-normalized event object at the official docs page
I have a page where I have to close a dialog when Esc is pressed. I wrote the following simplified code example for this task:
<html>
<head>
<script language="JavaScript">
function keyUpExample() {
alert('on' + event.type + ' event fired by ' + '"' + event.srcElement.id + '" ' + ' ' + event.which)
}
</script>
</head>
<body id="myBody" onkeyup="keyUpExample()">
Trying keyUp event: Press any key...
</body>
</html>
This works as expected under Chrome but is NOT working under IE 7. Is there any workaround on order to cope this problem?
Thanks in advance!
Key events don't have to be caught by the body, but document or window works across browsers. Also, keyCode returns the correct value for keyup or down events.
<!doctype html>
<html lang="en">
<head>
<meta charset= "utf-8">
<title>Small Page</title>
<html>
<head>
<script>
function keyUpExample(e){
e=e || window.event;
var who= e.target || e.srcElement;
alert(e.type+' caught at '+who.nodeName+ ': key #'+e.keyCode)
}
window.onload=function(){
document.onkeyup= keyUpExample;
document.body.onkeyup= keyUpExample;
}
</script>
</head>
<body>
Trying keyUp event: Press any key...
</body>
</html>
Pass event as an argument to the callback, and check for window.event for IE.
<html>
<head>
<script>
function keyUpExample(e) {
e = e || window.event;
alert('on' + e.type + ' event fired by ' + '"' + e.srcElement.id + '" ' + ' ' + e.which)
}
</script>
</head>
<body id="myBody" onkeyup="keyUpExample()">
Trying keyUp event: Press any key...
</body>
</html>
Demo
element.onkeyup reference
However
You're better off using a library which smooths out all the ugly cross-browser inconsistencies. Take your pick: jQuery, Prototype, YUI, Dojo, MooTools, RightJS...
Are you allowed to use jQuery? If so, then you can accomplish it with .keyup().
Using jQuery also means you can generally leave the cross-browser worries to somebody else.
try
function keyUpExample(e) {
var evt = e || event;
alert('on' + evt.type + ' event fired by ' + '"' + ((evt.srcElement)?evt.srcElement.id:evt.target.id) + '" ' + ' ' + ((evt.which)?evt.which:evt.keyCode))
}
It is actually very simple, a raw JavaScript solution could look kinda like this
function callback(event) {
if (event.keyCode == 27) {
alert('Here you go!');
}
}
if (document.addEventListener) {
document.addEventListener('keydown', callback, false);
} else {
document.attachEvent('onkeydown', callback);
}
Just attach it to the document no need for any onload trickery.
Also, as people suggested you, check RightJS, it's very lightweight and friendly, and you will be able to do things like those :)
http://rightjs.org/plugins/keys
In Gmail, for example, when one presses Ctrl + B, instead of it getting passed to the browser (which would normally bring up some sort of bookmark manager), it hijacks it for formatting purposes, i.e. turn on bold formatting for the message ur in the middle of comoposing. Same for Ctrl+i, Ctrl+u.
How is this done?
You would attach an onkeydown or onkeyup event handler to the global document object. For example, if I wanted to make the title bar change to "asdf" each time Ctrl-M was pressed, I would register the event handler through window.onload, like this:
window.onload = function()
{
document.onkeydown = function(event)
{
var keyCode;
if (window.event) // IE/Safari/Chrome/Firefox(?)
{
keyCode = event.keyCode;
}
else if (event.which) // Netscape/Firefox/Opera
{
keyCode = event.which;
}
var keyChar = String.fromCharCode(keyCode).toLowerCase();
if (keyChar == "m" && event.ctrlKey)
{
document.title = "asdf";
return false; // To prevent normal minimizing command
}
};
};
W3Schools has more information on using these events: onkeydown and onkeyup.
Also, I think I should note that there are some discrepancies across browsers in regards to the event properties (like, for example, in Firefox, you're supposed to access the keycode through event.which, while in IE it's event.keyCode, although Firefox may support event.keycode—confusing, isn't it?). Due to that, I'd recommend doing this stuff through a JavaScript framework, such as Prototype or jQuery, as they take care of all the icky compatibility stuff for you.
Here is the source for an HTML page that uses jQuery and does what htw's solution does.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Hijack Example</title>
<script type="text/javascript" src="../scripts/jquery-1.2.1.js">
</script>
<script type="text/javascript">
$(function(){
document.title = "before keypress detected";
$(document).keydown(function(event) {
// alert('stuff happened: ' + msg + " " + event.keyCode);
var keyChar = String.fromCharCode(event.keyCode).toLowerCase();
if (keyChar == "m" && event.ctrlKey) {
document.title = "ctrl-m pressed!";
}
});
});
</script>
</head>
<body id="body">
<p>Change the path to jquery above as needed (search for ../scripts/jquery-1.2.1.js)</p>
<p>Watch the title bar, then press control-M, then watch the title bar again!</p>
</body>
</html>
Hope this helps somebody!
Use the onkeydown or onkeyup event to fire a handler function:
var body = document.getElementsByTagName("body")[0];
body.onkeydown = function(event) {
var str = "";
for (var prop in event) {
str += prop + ": " + event[prop] + "<br>";
}
body.innerHTML = str;
};
With that you can see what properties an event object has.