How to bind multiple actions to a keyboard event [duplicate] - javascript

This question already has an answer here:
override existing onkeydown function
(1 answer)
Closed 7 years ago.
I am trying to make a chrome extension that modifies the text in an active text area of a Facebook chat window. But I want the change to take place only when the user presses the enter key so that the text doesn't change while it is still in the textarea. I want it to happen using javascript and make it feel like it's happening in the background although I want it to get triggered on the keydown event of the enter key.
Now the relevant JavaScript for the chat window's textarea in Facebook is:
<textarea class="blah"
onkeydown="window.Bootloader && Bootloader.loadComponents(["control-textarea"],
function() { TextAreaControl.getInstance(this) }.bind(this)); ">
</textarea>
And in my extension's JavaScript file. I bind the keydown event using something like this:
//elem is bound to the focussed textarea object
elem.onkeydown = function(evt) {
if(evt.keyCode == 13){
//Some javascript code I want to execute here...
}
};
I think as soon as the user presses the enter key, the textarea is cleared and some sort of a post request is made. So I lose the scope of the text I wanted to modify using JavaScript. I checked that the enter key binding is working for my extension by pressing shift + enter, and it modified the text without a problem. So my script is working fine.
However I want my script to be executed before the textarea is cleared and the post request is made. I just don't want the user to see the text getting modified.
Can I add/modify the keybinding of the textarea used by Facebook as shown above in my script for the google chrome extension? Any help is deeply appreciated.

There are a million duplicates of this question on here, but here goes again anyway:
You can use target.addEventListener(type, listener[, useCapture]); In your case, it would be
document.addEventListner(keypress, function(event) { //You can use keydown too
if (event.which === 13) { // Value for Enter key if keydown or keyup used, use event.keyCode
//some code that you want to add
}
}
If you are using jQuery, you can use
$(document).keypress(function(event){
if (event.which === 13) {
// Your code here
}
});
P.S. - In case of adding crossbrowser support, you should use something like this:-
if (target.addEventListener) {
target.addEventListener('keypress',myFunction,false);
}
else if(target.attachEvent) {
target.attachEvent('onkeypress', myFunction, false);
} else {
target.onkeypress = myFunction;
}
// Here myFunction is the callback where you would check for the character code and your custom code

Related

How to detect ENTER keypress/ or the "GO" button in the Address Bar?

I want to detect the ENTER keypress of the Address Bar and also, the "Go(to the specified URL)" button using Javascript.
As per my previous efforts using "keycode==13" did not work as required.
say, in the following code:
window.onkeypress = testKeyEvent;
function testKeyEvent(e) {
if (e.keyCode == 13) //We are using Enter key press event for test purpose.
{
alert('Enter key pressed');
}
else //If any other button pressed.
{
alert('Not Enter key pressed');
}
} </script>
I want first the Alert box to be displayed,after I have typed any URL(valid or not) in the address box and Pressed ENTER/ Clicked GO button and then go to specified URL.
Is it Possible? I know I am missing out on a lot of things, Please mention about them.
If I am interpreting your question correctly, I don't think you can do this, because the context in which the JavaScript runs stops at the Document (meaning, JavaScript doesn't even quite know that the browser itself exists).
You can't detect the keystroke because it's outside your window, but you can detect navigation away from your page like
window.onbeforeunload = function () {
alert("Leaving page...");
}

VueJS - How to detect Ctrl+V?

I've already seen the answers to this question, but it's not the solution I need, since it's for jQuery, and I need something for vue.js.
So far, I was able to detect single character presses using the ff. code:
export default {
name: 'game',
data () {
return {
allowInput: false,
disabledKeys: ['ArrowLeft', 'Home', 'Control']
}
},
methods: {
keymonitor: function (event) {
console.log(event.key)
if (this.disabledKeys.indexOf(event.key) >= 0) {
event.preventDefault()
this.allowInput = false
// alert('not allowed')
} else {
this.allowInput = true
}
},
checkAnswer () {
if (! this.allowInput) {
alert('the key(s) you pressed is/are not allowed')
}
} /* END checkAnswer */
} /* END methods */
} /* END export default */
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.2/vue.min.js"></script>
<input id="typeBox" ref="typeBox" autocomplete="off" placeholder="Type here..."
#keydown="keymonitor" #keyup="checkAnswer()" />
The code above successfully prevents the textbox from accepting ArrowLeft, Home, and Control key presses.
The problem:
I'm trying to figure out how to detect Ctrl+V, because I want to prevent paste action in my text box. Does anyone know how to do this? Thanks in advance.
To detect two keys, Vue provides modifier keys, For example to detect Alt+C, you can simply do:
<input #keyup.alt.67="YourFn">
Similarly for Ctrl+V, you can do:
<input #keyup.ctrl.76="YourFn">
As I can see here, ASCII code for Ctrl+v is 22, so you should be simply able to do :
<input #keyup.22="YourFn">
you can check the js fiddle link for the same
keyup: function(event){
if(event.keyCode == 86 && event.ctrlKey){
// do something here
}
}
https://jsfiddle.net/neelkansara28/wh61rby8/16/
I'm a little late to the party here but for anyone coming here with this same question, there is really no need for anything fancy that is not built into Vue itself. If you don't want to read through all of this
Here is a sandbox with a working example to play with
As the accepted answer says, vue has it's own event listeners as documented here
It also does not require key codes, specifically, to work. So in your case, it will accept the letter v
Below is an example of a vuetify component (although this will work with pretty much any element):
<v-text-field
v-model="textField"
#keydown.prevent.ctrl.v=""
#keydown.prevent.meta.v=""
#click.prevent.right.exact=""
/>
Here is the breakdown of the #stuff that you see there:
To prevent key combos like ctrl/cmd + v:
In the case of combos, in order to make it work, you'll have to listen to keydown instead of the alternatives
To account for Windows, you'll need to use #keydown.prevent.ctrl.v=""
To account for Mac, you'll need to use #keydown.prevent.meta.v=""
#keydown listens for the keydown event
.prevent automatically applies event.preventDefault()
.ctrl/.meta are the modifier keys you're listening for
the meta key is the CMD key on Mac and Windows key on Windows
v is, of course, the other key we are listening for
the empty "" just means we're not giving it a function to run. if you want to do anything additional, you can just simply reference a function here. like: #keydown.prevent.meta.v="doSomethingElse"
If you also want to prevent the right-click (context) menu: #click.prevent.right.exact=""
#click will listen to the click event.
.right is the modifier to listen for right-clicks only
.exact makes sure that no other modifiers are accepted. Without this, someone could press shift + right-click and the context menu would appear as normal. In this case, .exact makes sure we're doing something on any version of right-click

Shortcut keys for Javascript game GUI

I've been making a simple javascript based OOP text game that uses string replacement and variable adjustments tied to button .onclick events. I've been asked to add hotkeys for easier access, and I've been struggling with how to do it.
First I tried using the JSQuery hotkeys script and the .bind command, but that seemed like it would be very time consuming as I'd have to recode every .onclick as a hotkey, and even with unbind, it was firing off every event tied to the key on the script.
I feel like the best way to do would be if I could code the keys to the gui, i.e. if when you pressed "1", it activated the .onclick of button 1, that way the hotkey would be static (except when the button is disabled), but I've no idea how to do that. I've just been using html buttons, (i.e. input type="button" value="" disabled="disabled" id="button1"), I suspect I'd need something more sophisticated?
Thanks in advance for any help, google has been useless.
[EDIT - General description of code]
The way the game works is very simple, via the calling of functions as new events with different text/buttons (and different onclick events tied to those buttons). As an example, the start screen code is:
function startScreen() {
$(document).ready(function () {
$('#text').html("Game title and info");
$('#button1').val("Start Game");
$('#button1').attr("disabled", false);
$("#button1").one("click", function () {
textClear();
buttonClear();
nameScreen();
});
$("#button2").val("Load Game");
$('#button2').attr("disabled", false);
$("#button2").one("click", function () {
textClear();
buttonClear();
loadData();
});
$("#button6").val("Settings");
$('#button6').attr("disabled", false);
$("#button6").one("click", function () {
textClear();
buttonClear();
settingsScreen();
});
});
}
Since the code executed by button one changes between functions, what the hotkey does as well, which was my problem with using the JQuery library code.
When a key is pressed then the event onkeypress is fired. This event provides some values like:
keyCode
charCode
which
So you could do something like:
window.onkeypress = function (event) {
// the keyCode value for the key 1 is 49, for the key 2 is 50
if (event.keyCode == 49) {
// execute the same code as clicking the button 1
console.log("The key 1 was pressed.");
} else if (event.keyCode == 50) {
// execute the same code as clicking the button 2
console.log("The key 2 was pressed.");
}
};
Now, when a user visits your website he could press the keys 1 or 2 on the keyboard and fire the same logic as clicking the buttons "1" and "2" (being something like <input id="button1">) with the left mouse taste.
If you have really a lot of hotkeys then this would be also tedious to type, but without knowing your code I can hardly give you a complete solution. I hope my answer can give you some idea how to proceed further.
EDIT:
Further reading on the topic:
http://unixpapa.com/js/key.html

Capture delete key if not focused in a form

I have a web app which plots points with SVG, I want to add the ability to delete a selected point by pressing the delete key. I can capture delete keydown (or up) for the entire document and prevent the default event (Chrome's default behavior is to go back a page), however this obviously blocks all delete events so the delete button no longer works in forms.
Is there a way to set it up so that the delete key works as intended in forms/inputs but when anywhere else in the app it can be used as a custom delete function?
The first thing that came into my mind, is to stopPropagation on the input and textarea fields, then the preventDefault should not be triggered on the document.
JQuery pseudo code:
$('input, textarea').keypress(e, function(e){e.stopPropagation();});
$(document).keypress(e, function(e){if(delete) e.preventDefault();});
Another possiblity is the check the orignal target on the key event of the document.
Event callback:
var originalElement = e.srcElement || e.originalTarget;
if(orignalElement.tagName === 'INPUT' or orignalElement.tagName === 'TEXTAREA'){ return; }
// else do your delete key stuff
The first line should be obsolete, if you are using jQuery, because it normalized the event for you, and you can use e.target to get the originalTarget
My prefered approach would be something like this:
$(window).keyup(function(e) {
if(e.keyCode == 46 && $("input:focus, textarea:focus").length == 0) {
e.preventDefault();
alert("delete key pressed!");
}
});
However, I'm not sure if you'll be able to override the back button behaviour - it seems unlikely that Chrome would allow it, given the potential for abuse.

Jquery : how to trigger an event when the user clear a textbox

i have a function that currently working on .keypress event when the user right something in the textbox it do some code, but i want the same event to be triggered also when the user clear the textbox .change doesn't help since it fires after the user change the focus to something else
Thanks
The keyup event will detect if the user has cleared the box as well (i.e. backspace raises the event but backspace does not raise the keypress event in IE)
$("#inputname").keyup(function() {
if (!this.value) {
alert('The box is empty');
}
});
jsFiddle
As Josh says, this gets fired for every character code that is pressed in the input. This is mostly just showing that you need to use the keyup event to trigger backspace, rather than the keypress event you are currently using.
The solution by Jonathon Bolster does not cover all cases. I adapted it to also cover modifications by cutting and pasting:
$("#inputname").on('change keyup copy paste cut', function() {
//!this.value ...
});
see http://jsfiddle.net/gonfidentschal/XxLq2/
Unfortunately it's not possible to catch the cases where the field's value is set using javascript. If you set the value yourself it's not an issue because you know when you do it... but when you're using a library such as AngularJS that updates the view when the state changes then it can be a bit more work. Or you have to use a timer to check the value.
Also see the answer for Detecting input change in jQuery? which suggests the 'input' event understood by modern browsers. So just:
$("#inputname").on('input', function() {
//!this.value ...
});
Another way that does this in a concise manner is listening for "input" event on textarea/input-type:text fields
/**
* Listens on textarea input.
* Considers: undo, cut, paste, backspc, keyboard input, etc
*/
$("#myContainer").on("input", "textarea", function() {
if (!this.value) {
}
});
You can check the value of the input field inside the on input' function() and combine it with an if/else statement and it will work very well as in the code below :
$( "#myinputid" ).on('input', function() {
if($(this).val() != "") {
//Do action here like in this example am hiding the previous table row
$(this).closest("tr").prev("tr").hide(); //hides previous row
}else{
$(this).closest("tr").prev("tr").show(); //shows previous row
}
});
Inside your .keypress or .keyup function, check to see if the value of the input is empty. For example:
$("#some-input").keyup(function(){
if($(this).val() == "") {
// input is cleared
}
});
<input type="text" id="some-input" />

Categories

Resources