How to detect keypresses in jQuery regardless of layout? - javascript

So basically i am trying to connect clicking links to keys in Tampermonkey. First I tried e.which, but it didn't work with different layouts. Then I tried e.code, but for some reason it only detects pressing the B key (see code below). What did I do wrong?
$(document).on("keypress", function (e) {
if(e.сode == "KeyN") {
document.getElementById("nextimage").click();
} else if(e.code == "KeyB") {
document.getElementById("previmage").click();
}
});

You can try using the KEY itself instead of the code. The toUpperCase() function will detect lowercase or uppercase :
$(document).on("keypress", function (e) {
if(e.key.toUpperCase() == "N") {
alert("yay!")
} else if(e.key.toUpperCase() == "B") {
alert("nay");
}
});
Here's a reference with the different key codes: https://keycode.info/

Try this to read keys.
Make sure you have the JQuery reference.
$(document).keypress(function(event) {
alert('You pressed - ' + event.key.toUpperCase());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
and here is javascript in case:
const myText = document.getElementById('myText');
document.addEventListener('keypress', logKey);
function logKey(e) {
myText.textContent += e.key.toUpperCase();
if(e.key.toUpperCase() == 'N')
alert("You Pressed N key");
}
and
<p id="myText"></p>

Related

Javascript ALT click on link opens alternative link

I want to be able to open an alternate link when I click by holding down the alt button. I've tried some solutions but they seem to have weird problems. All I want is when clicking to detect if the alt key is held down
function selectlink(selection,alt) {
if (alt key is pressed) {
window.open(alt,'_blank');
} else {
window.open(selection,'_blank');
}
In the body:
Click
Preferably WITHOUT Jquery.
You have to reference the event as a parameter, this will make it possible to check if a key was pressed during the click.
function selectlink(selection, alt, e) {
if (e.altKey) {
alert(alt);
} else {
alert(selection);
}
}
Click
With a little bit of rewriting you can make the link a bit smarter and still have functioning links when javascript is disabled.
function selectLink(e) {
var el = e.target;
if (e.altKey) {
window.open(el.getAttribute("alternative"), '_blank');
e.preventDefault();
}
}
Click
Here's a solution using jQuery. I'll write a solution using pure JS in my lunch break.
https://jsfiddle.net/jotq0atz/2/
X
Here is the js:
$("#x").on('click', function(e){
link = $(e.currentTarget).attr('href');
alt_link = $(e.currentTarget).attr('data-alt-href');
if(e.altKey){
alert("alt was held while clicking");
window.open(alt_link, '_blank');
} else {
alert("alt wasn't held while clicking");
window.open(link, '_blank');
}
});
Here's a solution made by adapting the answer provided in javascript alt key
var altdown = false;
document.onkeydown = KeyCheck;
document.onkeyup = KeyCheck;
function KeyCheck(e)
{
var KeyID = (window.event) ? event.keyCode : e.keyCode;
switch(KeyID)
{
case 18:
document.Form1.KeyName.value = "Alt";
if(e.type == "keydown"){
altdown = true;
}
else if(e.type == "keyup"){
altdown = false;
}
break;
}
}
function selectlink(selection,alt) {
if (altdown) {
window.open(alt,'_blank');
} else {
window.open(selection,'_blank');
}
}
The link opened in dependent on the altdown variable which is true when the alt key is pressed down. A working fiddle can be seen here. https://jsfiddle.net/q5kr9h2o/7/

Jquery binding key to body except a class

I'm trying to bind a key to my entire page except to one class of elements.
$('*').not('.textarea-note').keypress(function (event) {
// if key pressed is space
if (event.which == 32) {
alert('space pressed');
event.preventDefault();
}
});
The problem is that I need to do the preventDefault() and when I'm in a textarea then I can't make a space caracter.
Am I doing something wrong or it's not possible to bind to everything except some class or something.
Thanks in advance !
Edit :
After the comment from Roland, I came up with this instead which is working perfectly.
$(document).keypress(function (event) {
// if key pressed is space
if (event.which == 32 && event.target.nodeName != "TEXTAREA") {
if (videoPlaying) {
pauseVideo();
} else {
playVideo();
}
event.preventDefault();
}
});
I think you are looking for this...
$(document).keypress(function(event) {
// if key pressed is space
if (event.which == 32) {
if (event.target.id !== "a1") {// for class $(event.target).attr('class')
alert('space pressed');
event.preventDefault();
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="a1"></textarea>
<textarea id="a2"></textarea>
<textarea id="a3"></textarea>

Javascript only when cursor focus within textbox

Is it possible to run a JavaScript function only when the cursor focus is in a specific textarea?
I want to perform an action on keypress of the enter key, however I don't want this event listner to be in place just generally on the page, rather only when the cursor is in the textarea I have (id is postcontent)
As an example, the function I'm using is this:
function onEnter(){
if(characterCode == 13)
{
console.log("Enter pressed");
}
}
Just as a start while I work out the focus issue...
I also have jQuery at my disposal.
div1.onfocus=
function onEnter(){
if(characterCode == 13)
{
console.log("Enter pressed");
}
}
Here is an alternative:
var textArea = document.getElementById("postcontent");
textArea.addEventListener("keypress", handleKeyPress, false);
function handleKeyPress(e) {
var characterCode = e.charCode;
if (characterCode == 13) {
console.log("Enter pressed");
}
}
Fiddle

Toggling a function that depends on a button state?

I'm trying to turn a button-click into a toggle that enables or disables a function, depending on its state. The function allows the enter key to be used for a form submission.
var enterToggle = true;
function enterToggleListener(elem) {
enterKeyPress();
elem.click(function() {
enterToggle = !enterToggle;
console.log('enter-toggle clicked')
if (enterToggle === false) {
console.log('enter toggle false')
// What do I need to add here to stop 'enterKeyPress()'?
} else {
console.log('enter toggle true')
enterKeyPress();
}
});
}
function enterKeyPress() {
$('#noteText').keypress(function(e){
if(e.which == 13){
$('#noteButton').click();
}
});
}
enterToggleListener($('#toggle-button'));
What I don't understand is how to stop the enterKeyPress() function when enterToggle is false. Any suggestions?
EDIT: Cleaned-up code, with #James Montagne's answer added
var enterToggle = true;
function enterToggleListener(elem) {
elem.click(function() {
enterToggle = !enterToggle;
if (enterToggle === false) {
$('#enter-toggle').text('Enter key saves note (OFF)')
} else {
$('#enter-toggle').text('Enter key saves note (ON)')
}
});
}
function enterKeyPress() {
$('#noteText').keypress(function(e){
if(enterToggle && e.which == 13){
$('#noteButton').click();
}
});
}
enterKeyPress();
enterToggleListener($('#enter-toggle'));
function enterKeyPress() {
$('#noteText').keypress(function(e){
if(enterToggle && e.which == 13){
$('#noteButton').click();
}
});
}
You can simply check the value of the variable within your handler. This way you don't need to keep adding and removing the handler as seems to be your current approach.
However, if you must add and remove for some reason, you would use off.

How to disable Enter/Return Key After a function is executed because of it?

I have this function where #text_comment is the ID of a textarea:
$('#text_comment').live('keypress',function (e) {
if(e.keyCode == 13) {
textbox = $(this);
text_value = $(textbox).val();
if(text_value.length > 0) {
$(this).prev().append('<div id="user_commenst">'+text_value+'</div>');
$(textbox).val("");
}
}
});
What is happening is the text is appending when the enter/return key is hit (keyCode 13), but it is also moving the text a line down, as the enter/return key is supposed to.
This is occurring even though I set the value of the textbox to "".
How about event.preventDefault()
Try and stop your event propagation (See http://snipplr.com/view/19684/stop-event-propagations/) when entering the if(e.keyCode == 13) case.
try this one event.stopImmediatePropagation()
$('#text_comment').live('keypress',function (e) {
if(e.keyCode == 13) {
e.stopImmediatePropagation()
///rest of your code
}
});
I've tested this out, this works. The enter does not create a new line.
$('#text_comment').live('keypress',function (e) {
if(e.keyCode == 13) {
textbox = $(this);
text_value = $(textbox).val();
if(text_value.length > 0) {
$(this).prev().append('<div id="user_commenst">'+text_value+'</div>');
$(textbox).val("");
}
return false;
}
});
Although I am wondering, if you don't want to ever have a new line, why are you using a textarea, why not use a input type='text' instead ?
Answer here http://jsfiddle.net/Z9KMb/

Categories

Resources