I'm having a small mental block: I've got a javascript function in html that writes the keycode when a key is pressed. I've got it hooked up to a function that tells me exactly what character and keycode is pressed (not included).
My question is how do I modify the code to print up keypress after keypress after keypress. At the moment it does just the one and then that's that.
There's a rather nicer version of what I'm doing here on css-tricks, with the code here
Admittedly the latter is running JS Babel which might be the difference. However, I need to do this in pure Javascript.
Bonus points: is keypress one word or two ;)
</script>
function check_keycode(e)
{
var keycode;
if (window.event)
{
keycode = window.event.keyCode;
}
else if (e)
{
keycode = e.which;
}
document.write("keycode: " + keycode);
//console.log("keycode: " + keycode);
}
</script>
I think you want some thing like this. I tried with chrome console.
HTML
<p id="log"></p>
JS:
const log = document.getElementById('log');
document.addEventListener('keypress', logKey);
function logKey(e) {
log.textContent += ` ${e.key}`;
}
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);
}
}
I have this code:
document.addEventListener("keydown", keyDownTextField, false);
function keyDownTextField(e) {
var keyCode = e.keyCode;
if(keyCode==13) {
alert("You hit the enter key.");
} else {
alert("Oh no you didn't.");
}
}
if i paste it in the template it works fine, but if i put it in external file, it doesnt work. Although all other javascript in the external file works fine.I have also tried with this code:
$(document).keydown(function(e){
if (e.keyCode == 37) {
alert( "left pressed" );
return false;
}
});
but the same story. What am i doint wrong?
Seems like this answer covers your problem.
Shortly: it matters which moment you add eventListener to the document.
It should be applied on windows.onload
Good day everyone!
I have a problem merging the codes in one function. (If it's possible).
First:
There is a table.
When the table row click two buttons will be enabled.
Here's the code:
function enableRegButton() {
$('#registerExist').prop('disabled', false);
$('#edit').prop('disabled', false);
// regButton execute when Enter key pressed
$(document).unbind("keyup").keyup(function(e){
var code = e.which; // recommended to use e.which, it's normalized across browsers
if(code==13)
{
$("#registerExist").click();
}
});
}
Second:
When Escape key pressed it will disable all bind buttons.
Here's the code:
$(document).keyup(function(e) {
if (e.keyCode == 27) { // escape key maps to keycode `27`
$('#registerExist').prop('disabled', true);
$('#edit').prop('disabled', true);
document.getElementById("enStudID").value = "";
document.getElementById("enInfoID").value = "";
document.getElementById("enCoffID").value = "";
document.getElementById("enYearID").value = "";
}
});
Now, what I want to do are those two codes above will merge in one function and it will call the function and trigger all those codes so when I edit the code it will be centralized.
Here's my final code:
function enableRegButton() {
$('#registerExist').prop('disabled', false);
$('#edit').prop('disabled', false);
// regButton execute when Enter key pressed
$(document).unbind("keyup").keyup(function(e){
var code = e.which; // recommended to use e.which, it's normalized across browsers
settings();
});
}
// This code is for ESC button when pressed.
$(document).keyup(function(e) {
settings();
});
function settings(){
if(code==13)
{
$("#registerExist").click();
}
else if (code==27){ // escape key maps to keycode `27`
$('#registerExist').prop('disabled', true);
$('#edit').prop('disabled', true);
document.getElementById("enStudID").value = "";
document.getElementById("enInfoID").value = "";
document.getElementById("enCoffID").value = "";
document.getElementById("enYearID").value = "";
}
}
Problem:
Only the enable button is working when table row is click
Pressing Escape key will not disable the enabled buttons.
Code won't run when pressing Enter Key.
You need to pass the key code to the settings method.
$(document).keyup(function(e) {
settings(e.keyCode);
});
function settings(code) {
Use the browser's developer console when debugging Javascript issues, it's an invaluable tool and picks up problems like this quite easily.
You are assigning the code variable in the unbind callback, not in the bind callback :)
I found a post on SO that was actually posted yesterday (I cannot find it now) that says my code below should work, but it does not -- the 'handleRtnKey(e)' function below is never called - why?
<input type="text" id="zer" onkeyup="handleRtnKey(e)"/>
// my javascript function -- by the way, I will not be using jquery.
function handleRtnKey(e)
{
alert("Just entered handleRtnKey()");
if (!e)
{
e = window.event; // resolve event instance for IE
}
alert("Just entered handleRtnKey(), e.keyCode is: " + e.keyCode);
alert("Just entered handleRtnKey(), e is: " + e);
if (e.keyCode == '13')
{
alert("handleRtnKey: got the RTN key up event.");
return false;
}
}
None of the alerts fire.
I found a SO post from yesterday that had this near exact code (without my alerts) that claimed to work fine (sorry I cannot re-find that SO post).
I need to use straight javascript (not jquery) to get the key code of the keyup event in my input text box -- that's all I need to do, and if it is the Return key, then I'll take some action, but for now I cannot get the above code to fire that handleRtnKey() function -- why?
EDIT
Damon introduced me to the keyword 'event' and the above code now works fine -- I simply renamed the argument in the html code from 'e' to 'event' and the javascript handler now works fine -- here is the only modification to the code above I had to make:
// OLD
<input type="text" id="zer" onkeyup="handleRtnKey(e)"/>
// NEW
<input type="text" id="zer" onkeyup="handleRtnKey(event)"/>
NOTE: the javascript function handleRtnKey(e) is unchanged, there was no reason for my to change that function's signature, it looks like below and works fine now:
function handleRtnKey(e)
{
alert("Just entered handleRtnKey()");
if (!e)
{
e = window.event; // resolve event instance for IE
}
alert("Just entered handleRtnKey(), e.keyCode is: " + e.keyCode);
alert("Just entered handleRtnKey(), e is: " + e);
if (e.keyCode == '13')
{
alert("handleRtnKey: got the RTN key up event.");
return false;
}
}
THANKS DAMON.
you don't need argument at all, just use event:
function handleRtnKey() {
event = event || window.event; // for cross-browsing
alert(event); // or do whatever you want with it
};
DEMO
The problem is that you call the method with parameter which you don't have. e is not declared. If you remove it it will work. This code worked for me:
<input type="text" id="zer"/>
<script>
window.onload = function () {
document.getElementById("zer").onkeyup = function(event) {
if (event.keyCode == 13) {
alert("Just entered handleRtnKey()");
}
};
};
</script>
The solution to my problem was as Damon pointed out in his comments above -- I was not aware there was a predefined 'event' keyword and when I used 'event' instead of 'e' in my code above, it worked fine.
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!