I\'m coding a function in jquery that executes if Ctrl+R is pressed but I can\'t seem to find out what the left and right ctrl keycodes are... Can some
event.key
and modern JS!$(document).keypress(function(event) {
if (event.key === "r" && event.ctrlKey) {
// Do something
}
});
or without jQuery:
document.addEventListener("keypress", function onEvent(event) {
if (event.key === "r" && event.ctrlKey) {
// Do something better
}
});
Mozilla Docs
Supported Browsers
$(document).ready(function () {
$(document).keyup(function (e) {
if (e.keyCode == 81 && e.ctrlKey) { //CTRL+Q
alert("CTRL+Q");
} else if (e.keyCode == 27) { //ESCAPE
alert("escape");
} else if (e.keyCode == 67 && e.altKey) { // ALT+C
alert("ALT+C");
}
});
});
key codes
Here is an entire list of keycodes that you can use.
@HostListener('window:keydown', ['$event'])
keyEvent(event: KeyboardEvent) {
if (event.ctrlKey && event.keyCode == 82)
{
}
}
This is the code I'm using to disable refresh on IE and firefox (This works well for F5, Ctrl+F5 and Ctrl+R)
<script language="javascript" type="text/javascript">
//this code handles the F5/Ctrl+F5/Ctrl+R
document.onkeydown = checkKeycode
function checkKeycode(e) {
var keycode;
if (window.event)
keycode = window.event.keyCode;
else if (e)
keycode = e.which;
// Mozilla firefox
if ($.browser.mozilla) {
if (keycode == 116 ||(e.ctrlKey && keycode == 82)) {
if (e.preventDefault)
{
e.preventDefault();
e.stopPropagation();
}
}
}
// IE
else if ($.browser.msie) {
if (keycode == 116 || (window.event.ctrlKey && keycode == 82)) {
window.event.returnValue = false;
window.event.keyCode = 0;
window.status = "Refresh is disabled";
}
}
}
</script>
If you don't want to use useragent to detect what type of browser it is ($.browser uses navigator.userAgent to determine the platform), you can use
if('MozBoxSizing' in document.documentElement.style)
- returns true for firefox
We can also use Ascii code for finding the characters as well as the characters
$('html').keydown(function (e) {
keydownfunc(e);
});
function keydownfunc(e) {
if (e.ctrlKey && (e.key === "r" || e.key === "R")) {
alert("ctrl+R");
}
}