keyboard shortcut using javascript not working - javascript

I am using command + h as a shortcut key in my website. It is not doing the function to be done. After I click something on the window only it works flawlessly. Here is my code..
window.onkeydown = function(event) {
if (event.keyCode == 72 && (event.metaKey == true)) {
//some function
}
}
Somebody try to rectify . I have included this code only after the dom gets loaded

window.onkeydown will only work if it is focused. So on body load you should set focus.
<body onload="setFocus()">
function setFocus(){
window.focus();
}
Working DEMO HERE

You could probably make it work with focusing the body on window load with document.body.focus() and attaching an event listener like this:
window.onload = function() {
document.body.focus();
document.addEventListener("keydown", keyDownFunction, false);
};
function keyDownFunction(event) {
if(event.keyCode == 72 && (event.metaKey == true)) {
alert("You hit the right keys.");
}
}

Related

Send an alert when user tabs into an iframe

I'm trying to make an alert box pop up when a user tabs into an iframe. I can't get the alert box to pop up.
document.addEventListener("keydown", function(event) {
if (event.which == "9") {
let iframeSelector = document.querySelector("iframe")
if (document.activeElement == iframeSelector) {
alert("test");
}
}
})
I was able to get this to work by adding a setTimeout of 0 around your if statement, like this:
document.addEventListener("keydown", function(event) {
if (event.which == "9") {
let iframeSelector = document.querySelector("iframe")
setTimeout(() => {
if (document.activeElement == iframeSelector) {
alert("test");
}
}, 0)
}
})
I believe this happens because when the keydown event fires, the activeElement is still the previous focused thing. It seems like it should then work with keyup instead, but in my testing it doesn't.
So this solution seems a little hacky, but it did work in my testing.

How to run function in function

I have this function, it should track ctrk+enter keys and send message. But function don't work. But if i call HotKeys(); in console, it works. So how to trigger it when script loaded? I new to javascript. Thanks and sry for my english.
function HotKeys() {
$('#msgbox').keydown(function (e) {
if (e.ctrlKey && e.keyCode == 13) {
document.getElementById("go").click();
}
});
}
HotKeys();
You can trigger the function on load by using:
window.onload = HotKeys();
If you want the function to be run anytime the hot keys are pressed, remove the function declaration around it so you just have the function body
Don't use a function, but attach a document ready handler like that:
$(document).ready(function() {
$("#msgbox").keydown(function (e) {
if (e.ctrlKey && e.keyCode == 13) {
$("#go").click();
}
});
});
This will register your handler when the document is ready. with your code, you indeed had to call HotKeys in order to register the handler.
try this
(function HotKeys() {
$('#msgbox').keydown(function (e) {
// when user presses ctrl + enter, click the "go" button
if (e.ctrlKey && e.keyCode == 13) {
document.getElementById("go").click();
}
});
})();

jquery keyup not firing

I use the following function on keyup event to redirect to another javascript function.
Problem is it does'nt seem to fire, although it does bind the function to the textbox.
$(document).ready(function () {
EnablePickTargetButton();
//clear contents; use a delay because tinyMCE editor isn't always fully loaded on document.ready
var t = setTimeout(function () {
if (typeof textEditorForCreate != 'undefined' && tinymce.editors.length > 0)
tinyMCE.activeEditor.setContent('');
}, 300);
var txtSearchUser = $('#txtSearchUser');
if(typeof txtSearchUser != 'undefined')
{
$('#txtSearchUser').keyup(function (e) {
if (e.keyCode == 13) {
e.preventDefault();
searchUser();
}
else
alert('cucu');
});
}
});
Not even the alert shows up. Checking the html, I can see it doesn't add onkeyup to the textbox; The textbox is in a popup window hosted in a div on the form; But on document.ready it runs the function without error.
Try this delegate on document or closest static element. (If the element is added dynamically)
$(document).on('keyup','#txtSearchUser',function(){
//Code
});
it works :
$(document).ready(function(){
$('#txtSearchUser').keyup(function (e) {
if (e.keyCode == 13) {
e.preventDefault();
}
else
alert('cucu');
});
});
http://jsfiddle.net/jMk5S/
check if you're referencing your html element properly. Perhaps you mix id with the class?
I edited your code and is working :
The problem is in your document ready function , you have a syntax error , next time check console in your browser to see what's wrong :
DEMO HERE
$(document).ready(function () {
//EnablePickTargetButton();
//clear contents; use a delay because tinyMCE editor isn't always fully loaded on document.ready
var t = setTimeout(function () {
if ($('#textEditorForCreate').length != 0 && tinymce.editors.length > 0)
tinyMCE.activeEditor.setContent('');
}, 300);
if($('#txtSearchUser').length!=0)
{
$('#txtSearchUser').keyup(function (e) {
if (e.keyCode == 13) {
e.preventDefault();
searchUser();
}
else
alert('cucu');
});
}
});

How to Disable the CTRL+P using javascript or Jquery?

Here I tried to disable the Ctrl+P but it doesn't get me alert and also it shows the print options
jQuery(document).bind("keyup keydown", function(e){
if(e.ctrlKey && e.keyCode == 80){
alert('fine');
return false;
}
});
http://jsfiddle.net/qaapD/10/
I am not sure how can I disable the Ctrl+P combination itself using jQuery or JavaScript.
Thanks
You can't prevent the user from printing, but you can hide everything when the user prints the document by using simple CSS:
<style type="text/css" media="print">
* { display: none; }
</style>
Updated fiddle.
If you would like to show the visitor a custom message when he/she try to print rather then just a blank page, it's possible with client side code but first wrap all your existing contents like this:
<div id="AllContent">
<!-- all content here -->
</div>
And add such a container with the custom message:
<div class="PrintMessage">You are not authorized to print this document</div>
Now get rid of the <style type="text/css" media="print"> block and the code would be:
if ('matchMedia' in window) {
// Chrome, Firefox, and IE 10 support mediaMatch listeners
window.matchMedia('print').addListener(function(media) {
if (media.matches) {
beforePrint();
} else {
// Fires immediately, so wait for the first mouse movement
$(document).one('mouseover', afterPrint);
}
});
} else {
// IE and Firefox fire before/after events
$(window).on('beforeprint', beforePrint);
$(window).on('afterprint', afterPrint);
}
function beforePrint() {
$("#AllContent").hide();
$(".PrintMessage").show();
}
function afterPrint() {
$(".PrintMessage").hide();
$("#AllContent").show();
}
Code is adopted from this excellent answer.
Updated fiddle. (showing message when printing)
After much testings on various browsers, it is easier to intercept the keys when they are down (not pressed) because some of this "App integrated keys" are difficult to intercept with the "keypress" event.
I came up with this script that is sort of cross browser compatible (I didn't test for Microsoft's IE). Notice that the browsers return different codes for some keys. In my case I wanted to prevent Ctrl+P.
The key "P" on chrome is seen as e.keyCode == 80, on opera, it is e.charCode == 16, while on firefox it is e.charCode == 112
$(document).on('keydown', function(e) {
if((e.ctrlKey || e.metaKey) && (e.key == "p" || e.charCode == 16 || e.charCode == 112 || e.keyCode == 80) ){
alert("Please use the Print PDF button below for a better rendering on the document");
e.cancelBubble = true;
e.preventDefault();
e.stopImmediatePropagation();
}
});
I used jQuery.
This is basically Peters answer from above. The difference is I added the accountability for mac when pressing the cmd+p button combo to print a page.
$(document).on('keydown', function(e) {
if((e.ctrlKey || e.metaKey) && (e.key == "p" || e.charCode == 16 || e.charCode == 112 || e.keyCode == 80) ){
alert("Please use the Print PDF button below for a better rendering on the document");
e.cancelBubble = true;
e.preventDefault();
e.stopImmediatePropagation();
}
});
To disable Ctrl+P printing by using javascript use below code:
window.addEventListener('keydown', function(event) {
if (event.keyCode === 80 && (event.ctrlKey || event.metaKey) && !event.altKey && (!event.shiftKey || window.chrome || window.opera)) {
event.preventDefault();
if (event.stopImmediatePropagation) {
event.stopImmediatePropagation();
} else {
event.stopPropagation();
}
return;
}
}, true);
Your code works in the jsfiddle example? What browser are you using? Itested it with the latest chrome and it worked fine.
You can also add:
e.preventDefault();
This Actually worked for me in chrome. I was pretty suprised.
jQuery(document).bind("keyup keydown", function(e){
if(e.ctrlKey && e.keyCode == 80){
Print(); e.preventDefault();
}
});
Where Print is a function I wrote that calls window.print(); It also works as a pure blocker if you disable Print();
As noted here: https://stackoverflow.com/a/20121038/2102085
window.print() will pause so you can add an onPrintFinish or onPrintBegin like this
function Print(){
onPrintBegin
window.print();
onPrintFinish();
}
(Again this is just chrome, but Peter has a downvoted solution below that claims the keycodes are different for ff and ie)
had a journy finding this, should be canceled on the keydown event
document.addEventListener('keydown',function(e){
e.preventDefault();
return false;
});
further simplified to :
document.onkeydown = function(e){
e.preventDefault();
}
given you have only one keydown event
there are some shortcuts you simply can't override with javascript, i learned it the hard way. I suppose CTRL+P is one of them.
one way to override them would be to deploy a chrome pacakged app.
Try this
//hide body on Ctrl + P
jQuery(document).bind("keyup keydown", function (e) {
if (e.ctrlKey && e.keyCode == 80) {
$("body").hide();
return false;
}
});
Here is the code, it work for me
document.addEventListener("keydown", function(event) {
if (event.ctrlKey && event.key === "p") {
event.preventDefault();
}
});
<script>
function isKeyPressed(event)
{
if(event.ctrlKey == 1)
{
alert("Please Submit exam form befor printing");
}
}
</script>
<body onkeydown="isKeyPressed(event)">
<p>this is the solution</p>
</body>
If you want to disable printing of your webpage you're wasting your time: it can't be done. Even if you work out how to capture CTRL-P users can still use the browsers menu bar to find the print command, or they can take a screen shot of the browser.
Stop trying to control the user, put your energy into making your site / app more useful, not less useful.
edit 2016: in the 3 years this has been up it has gathered 3 downvotes. I'm still not deleting it. I think it is important to tell fellow developers when they are given impossible tasks, or tasks that make no sense.
edit 2018: still think it's important that people that have this question read this answer.

how to re-enable default after doing event.preventDefault()

I know this exact question was asked here, but the answer didn't work for what I needed to do so I figured I'd give some example code and explain a bit...
$(document).keypress(
function (event) {
// Pressing Up or Right: Advance to next video
if (event.keyCode == 40 || event.keyCode == 39) {
event.preventDefault();
$(".current").next().click();
}
// Pressing Down or Left: Back to previous video
else if (event.keyCode == 38 || event.keyCode == 37) {
event.preventDefault();
$(".current").prev().click();
}
}
);
It basically disables the arrow keys to use them for something else, but doing:
$(document).keypress(function () { });
doesn't enable the default function again... I need it to scroll the page without having to create a scroll function for it...
Any ideas?
Thanks,
Matt
Adding a new handler doesn't replace the previous one, it adds a new one. You may be looking for jQuery#unbind if you're trying to remove the previous handler, but if you're going to be turning this on and off a lot, you probably would be better off with a flag telling you whether to prevent the default or not in your existing handler.
Adding, and later removing, a handler looks like this:
function keypressHandler() { /* ... */};
$('#thingy').keypress(keypressHandler);
// ...elsewhere...
$('#thingy').unbind('keypress', keypressHandler);
I'm not sure this is the right way to handle it.
A better way to approach this problem would be to put some kind of check inside your document.keypress instructions.. like..
var enableKeys = false;
$(document).keypress(
function (event) {
// Pressing Up or Right: Advance to next video
if (event.keyCode == 40 || event.keyCode == 39 && enableKeys) {
event.preventDefault();
$(".current").next().click();
}
// Pressing Down or Left: Back to previous video
else if (event.keyCode == 38 || event.keyCode == 37 && enableKeys) {
event.preventDefault();
$(".current").prev().click();
}
}
);
Then control the enablekeys wherever you feel necessary, either with a hover, or something along those lines.
function(e){ e.preventDefault(); }
and its opposite
function(e){ return true; }
Why not just wrap a condition around event.preventDefault(); in your current code?
Try to unbind the keypress event from document.
I don't know of any other ways to do it.
HTH

Categories