This question already has answers here:
Cancel the keydown in HTML
(6 answers)
Closed 9 years ago.
I am not sure how to do 'keydown' with pure JavaScript.
Here's how I did it with jQuery, but is there a way to do the same thing with pure JS also ?
I just wanna check if there is a way and to learn how to do it, as well as to see difference and length of code. Thank you.
$('body').on('keydown', function(e) {
if (e.keyCode === 27) return false;
});
EDIT: It is used to disable "Esc" button!
I don't like setting the listeners as attributes, so I add even listeners like this:
var ele = document.getElementById('test');
ele.addEventListener('keydown', function() {
//code
}, false);
Here you go
document.body.onkeydown = function(e) {
if (e.keyCode === 27) return false;
}
As you can see jQuery is shorter but this will execute less code
In pure javascript it is done this way
document.body.onkeydown=function(e){
key=e.keyCode || e.charCode|| e.which; //cross browser complications
if(key===27){
return false;
}
}
Hope it helped, it is the same script as the JQuery one you provided
Try this,
HTML
<body onkeydown="YourFunction(event)">...</body>
JS
function YourFunction(e)
{
var unicode=e.keyCode || e.charCode|| e.which;
if(unicode == 27)
return false;
else
{
//Your code...
}
}
Related
I would like to detect when the user clicks the tab key on their keyboard, using Javascript.
I've tried this:
document.onkeypress = (e) => {
console.log(e);
}
And there it logges keys like letters, numbers and charcters, but not tab, ecs, backspace, enter or other keys like those.
Is there any way of doing so?
Edit: btw, I can only use pure Javascript for this project, no libraries like jQuery etc.
The comment on your question, gives you jQuery solution that will not work.
You need to do it this way with vanilla JS. keyCode is property on event object, that stores the pressed keyboard button.
Here, you have all keycodes that you can use
https://css-tricks.com/snippets/javascript/javascript-keycodes/
document.onkeydown = (e) => {
if(e.keyCode === 9) {
console.log(e);
}
}
Try this
document.addEventListener("keydown", function(event) {
console.log(event.which);
})
https://css-tricks.com/snippets/javascript/javascript-keycodes/
You can use keydown instead.
document.onkeydown = function(e){
document.body.textContent = e.keyCode;
if(e.keyCode === 9){
document.body.textContent += ' Tab pressed';
}
}
Tabkey is an event code. You can catch that event and use e.keyCode ===9 to get the Tab. I think it will still go to the next element in the tabIndex so you will need to preventDefault as well.
I took a couple of things from the different answers on my post, and I got it to work.
document.onkeydown = (e) => {
if(e.key === 'Tab') {
console.log(e.key);
}
}
This question already has answers here:
How to combine keypress & on click function in JavaScript?
(5 answers)
Closed 5 years ago.
I have the following two functions:
$("input").keypress(function(event) {
if (event.which == 13) {
//code
}
});
$('#login_submit').click(function () {
//code
});
The code which is being used in the functions are EXACTLY the same code, basically code duplication. So i was wondering if there is a way to combine these functions with an AND statement?? There is an question on Stack but it aks for an OR logic. If you want the OR solution here
EDIT: I am trying to make somthing like an explorer. Now I want to hold "shift" and click on an "input" to mark them all. So i need the "onclick" on my input element to be true AND my keydown to be true.
After your edit, I believe what you are looking for is something like the following.
var shift_hold = false;
$(document).keydown(function(e) {
if(e.which === 16) {
shift_hold = true;
}
})
$(document).keyup(function(e) {
if(e.which === 16) {
shift_hold = false();
}
})
$('input').click(function() {
if(shift_hold) {
//your code here
}
})
I want to hold "shift" and click on an "input" to mark them all. So I need the "onclick" on my input element to be true AND my keydown to be true.
Within the click event, you can check if a key is also pressed down (click and key-is-down).
You can use the event object to see which keys are pressed. shift/control/alt have their own explicit properties.
Example:
$("input").click(function() {
console.log(event.shiftKey)
if (event.shiftKey) {
$(this).addClass("selected")
} else {
$(this).removeClass("selected")
}
// could use .toggleClass("selected", event.shiftKey) here,
// shown expanded for clarity
});
.selected {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Shift-click input to select, click to unselect
<input type='text'>
<input type='text'>
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Keyboard shortcuts with jQuery
I want to display a popover window using a shortcut key instead of clicking the icon on the toolbar.
Do you have any good idea?
Thank you for your help.
Abody97's answer tells you how to determine if a certain key combo has been pressed. If you're not sure how to get that key combo to show the popover, this is what you need. Unfortunately, Safari makes this needlessly complicated.
In the global script, you'll need a function like the following to show a popover, given its ID and the ID of the toolbar item that should show it:
function showPopover(toolbarItemId, popoverId) {
var toolbarItem = safari.extension.toolbarItems.filter(function (button) {
return button.identifier == toolbarItemId && button.browserWindow == safari.application.activeBrowserWindow;
})[0];
var popover = safari.extension.popovers.filter(function (popover) {
return popover.identifier == popoverId;
})[0];
toolbarItem.popover = popover;
toolbarItem.showPopover();
}
You'll also need code to call this function in your global script's message listener, like the following (this sample does not assume you already have a message listener in place):
safari.application.addEventListener('message', function (e) {
if (e.name == 'Show Popover') {
showPopover(e.message.toolbarItemId, e.message.popoverId);
}
}, false);
Finally, in your injected script, the function that listens for the key combo needs to call dispatchMessage, as below:
safari.self.tab.dispatchMessage('Show Popover', {
toolbarItemId : 'my_pretty_toolbar_item',
popoverId : 'my_pretty_popover'
});
(Stick that in place of showPopUp() in Abody97's code sample.)
Note: If you only have one toolbar item and one popover (and never plan to add more), then it becomes much simpler. Assuming you've already assigned the popover to the toolbar item in Extension Builder, you can just use
safari.extension.toolbarItems[0].showPopover();
in place of the call to showPopover in the global message listener, and omit the message value in the call to dispatchMessage in the injected script.
Assuming your shortcut is Ctrl + H for instance, this should do:
var ctrlDown = false;
$(document).keydown(function(e) {
if(e.keyCode == 17) ctrlDown = true;
}).keyup(function(e) {
if(e.keyCode == 17) ctrlDown = false;
});
$(document).keydown(function(e) {
if(ctrlDown && e.keyCode == 72) showPopUp(); //72 is for h
});
Here's a reference for JavaScript keyCodes: little link.
Here's a little demo: little link. (It uses Ctrl + M to avoid browser-hotkey conflicts).
I believe this could help you: http://api.jquery.com/keypress/
In the following example, you check if "return/enter" is pressed (which has the number 13).
$("#whatever").keypress(function(event) {
if( event.which == 13 ) {
alert("Return key was pressed!");
}
});
How to overwrite or remove key events, that is on a website? I'm writing a script for GreaseMonkey and I want to make event on Enter button, but when I press the ENTER button, it triggers function on website.
EDIT 1: Here is the website, that I need to do this http://lockerz.com/auth/express_signup
One of these two should do it for you. I used the first one, although someone on SO told me the second one will work also. I went for the hammer.
Sorry, first one wasn't a cut and paste answer. I use using it to return up/down arrow control on a website. I changed it so that it identifies keycode 13 instead.
(function() {
function keykiller(event) {
if (event.keyCode == 13 )
{
event.cancelBubble = true;
event.stopPropagation();
return false;
}
}
window.addEventListener('keypress', keykiller, true);
window.addEventListener('keydown', keykiller, true);
})();
Searching quickly on SO:
jQuery Event Keypress: Which key was pressed?
Code from there:
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) { //Enter keycode
//Do something
}
Without a library, use: http://jsfiddle.net/4FBJV/1/.
document.addEventListener('keypress', function(e) {
if(e.keyCode === 13) {
alert('Enter pressed');
return false;
}
});
Apologize if this is answered already. Went through some of the related questions and google, but ultimately failed to see why this isn't working.
My code is as follows
<iframe id="editor"></iframe>
editorWindow = document.getElementById('editor').contentWindow;
isCtrlDown = false;
function loadEditor()
{
editorWindow.document.designMode = "on";
editorWindow.document.onkeyup = function(e) {
if (e.which == 91) isCtrlDown = false;
}
editorWindow.document.onkeydown = handleKeyDown;
}
function handleKeyDown(e)
{
if (e.which == 91) isCtrlDown = true;
if (e.which == 66 && isCtrlDown) editFont('bold');
if (e.which == 73 && isCtrlDown) editFont('italic');
}
function editFont(a,b)
{
editorWindow.document.execCommand(a,false,b);
editorWindow.focus();
}
This code works perfectly in Chrome, but the keyboard shortcuts do not work in Firefox. In fact, in Firefox it does not seem to register the events for keyup/keydown at all.
Am I doing something grossly wrong here that is mucking up Firefox?
For editable documents, you need to use addEventListener to attach key events rather than DOM0 event handler properties:
editorWindow.document.addEventListener("keydown", handleKeyDown, false);
If you care about IE 6-8, you will need to test for the existence addEventListener and add the attachEvent equivalent if it is missing.
Try using:
editorWindow = document.getElementById('editor').frameElement;
I'm not sure this will solve the issue, it may also be:
editorWindow = document.getElementById('editor').contentDocument;
Or even possibly:
editorWindow = document.getElementById('editor').frameElement.contentDocument;
One thing you can do is put the entire string in a try statement to catch any errors and see if the content is being grabbed from within the iframe.
try { editorWindow = document.getElementById('editor').contentWindow; } catch(e) { alert(e) };
The only other thought I have is that you're typing into a textbox which is within an iframe, and you may possibly have to add the onkeydown event to that specific item, such as:
var editorWindow = document.getElementById('editor').contentDocument;
var textbox = editorWindow.getElementById('my_textbox');
function loadEditor()
{
editorWindow.document.designMode = "on";
textbox.onkeydown = function(e) {
alert('hello there');
}
}
I hope one of these is the solution. I often find when it comes to cross-platform functionality it often boils down to a little trial and error.
Good Luck!