VueJS - How to detect Ctrl+V? - javascript

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

Related

Javascript click event on anchor not working

I was trying to call the click event when hitting spacebar on keyboard on an anchor like so.
$("a").on("keypress", function (e) {
if (e.which === 32) {
$(this).click();
e.preventDefault();
}
}
This does not work however. I finally figured out a fix but I don't understand why it works. The simple fix was changing $(this).click() to $(this)[0].click()
What is the [0] doing and how is it making the click event work on the anchor?
Note: I also tried $(this).trigger("click") with no luck either.
See Roman Starkov's answer in the following link:
Jquery how to trigger click event on href element
The native DOM method does the right thing:
$('.cssbuttongo')[0].click();
^
Important!
This works regardless of whether the href is a URL, a fragment (e.g.
#blah) or even a javascript:.
Note that this calls the DOM click method instead of the jQuery click
method (which is very incomplete and completely ignores href).
So basically when you use the indexer you'll access the DOM's native click method instead of the jQuery implementation which does not work for links.
I wanted to mark this topic as duplicated but first I linked a wrong topic so I retracted the flag and now I cannot mark it again. So if someone has the power feel free to mark it as the duplicate of the linked topic. And if this answer helped upvote Roman Starkov's original answer in the link, he deserves it.
I didn't understanda exactly the scenario but that works for me, please try this:
$('a').click(function() {
alert('click...!');
});
//press enter on text area..
$('a').keypress(function(e) {
var key = e.which;
console.log('checking press key: ' + key)
if (key == 32) // the enter key code
{
$('a').click();
}
});
Feel free to rearrange...hope it helps!

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

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

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

How can I put a button in the down state?

Suppose I have a button, which goes into a down state when someone clicks on it, but before the mouse is released.
Now suppose instead that someone presses the 'a' key, I want the button to go into the down state, until the key is released, at which point it is triggered. Is this possible?
After dooing some research here is the final answer I got:
You can trigger mousedown or mouseup events on a button element using keyup and keydown
if your button is programmed to change its style according to these events than you are good to go.
See this fiddle example: http://jsfiddle.net/FwKEQ/15/
Note that if you use jQuery's UI components than it does work. But for standard buttons there is no way that you can move them to their pressed state using javascript
html:
<button id="jQbutton">Press 'A' to move me to pressed state</button>
Javascript:
<script>
$( "#jQbutton" ).button();
$(document).keydown(function(event) {
if ((event.keyCode === 97)||(event.keyCode === 65))
$("#jQbutton").mousedown();
});
$(document).keyup(function(event) {
if ((event.keyCode === 97)||(event.keyCode === 65))
$("#jQbutton").mouseup();
});
</script>
EDIT:
There might be a hack that we could utilize:
using accesskey for the button element and then try to simulate the accesskey press (that i am not sure if possible)
here is where i'm at so far http://jsfiddle.net/FwKEQ/28/
EDIT 2:
So looking further into this topic i have found the following:
Default buttons (without styles) are rendered by the OS, I was not able to find a formal proof for that but if you try to load the same page using a mac OS you'll get mac OS style buttons while in windows you will get the "ugly" gray button.
Because the default buttons are rendered by the OS they comply to OS events meaning events that are sent by the browser and are trusted.
this is not true for custom styled buttons as they comply to CSS an JS to change their appearance on press that is why the JQ button is affected by JS.
so to summarize you would need a trusted press event to fire on a default button to change its style and that cannot be done due to security constraints.
read a bit more about trusted events here: http://www.w3.org/TR/DOM-Level-3-Events/#trusted-events
and if someone could find a formal reference with regards to the default buttons being rendered by the OS please comment or edit this answer.
Unfortunately the rendering of the active state on default buttons neither
is a simple matter of css styling nor can be easily changed by applying
javascript.
An option to do this on default buttons is to use the hotkeys jquery plugin: https://github.com/jeresig/jquery.hotkeys or implement alternative key codes for different browsers.
and to apply 50% opacity to the default button when pressed (to indicate the keydown).
(To me it seems almost perfect ;-) It probably is as good as it can easily get to work across platforms and browsers using default buttons.
jsfiddle DEMO
and the code ...
html:
<button id="test">Test Button</button>
Selected: <span class="selected" id="out"></span>
javascript:
$('#test').click(function () {
fn_up();
});
fn_down = function(event){
$('#test').css("opacity", 0.5);
$('#test').focus();
event.preventDefault();
}
fn_up = function(event){
$('#test').css("opacity", 1);
$('#out').append(" test");
event.preventDefault();
}
//to bind the event to the 'a' key
$(document).bind('keydown','a', fn_down);
$(document).bind('keyup','a', fn_up);
//to get the same effect with the 'space' key
$(document).bind('keydown','space', fn);
$(document).bind('keyup','space', fn2);
In the fiddle I apply it to the space button and the mousedown/up to achieve the same effect with all events (but you could just use it with the 'a' key ... this is a matter of taste).
Here is a jsfiddel that shows how it's done using jQuery: http://jsfiddle.net/KHhvm/2/
The important part:
$("#textInput").keydown(function(event) {
var charCodeFor_a = 65;
if ( event.which == charCodeFor_a ) {
// "click" on the button
$('#button').mousedown();
// make the button look "clicked"
$('#button').addClass('fakeButtonDown');
// do some stuff here...
// release the button later using $('#button').mousedown();
}
});
The button event is triggered when entering "a" in the input field. But as Mark pointed out you need to fake the styling for the clicked button because the browser doesn't do it.
Edit: I'm not sure if you're using jQuery in your project. I just wanted to show that it is possible at all. If it can be done with the jQuery library there is also a way to do it in pure javascript. ;)

how to remove the default focus on submit button in HTML form?

I have a HTML form on my page. When i am putting some value in one of the text fields in form and press 'Enter key' the form gets submitted instantly. I think this is happening due to default focus is on submit button. But i try to remove that focus using blur() function, it is not working. I am using Chrome.
Is there any way to avoid this scenario?
All suggestions are welcome. thanks in advance.
The Submit button is not actually focused; Enter in a text field is supposed to submit the form.
You could register a handler for the submit event, and then only allow it if the Submit button was actually focused at the time submit was requested.
However, you'll be deliberately breaking the way that HTML forms work. Not everyone wants to submit the form using the One True Way of actually clicking the Submit button (also, you'll be breaking accessibility and may introduce browser-specific bugs).
No. The focus is still on the text field. Pressing enter there is supposed to submit the form (and bypasses the submit button entirely).
You can suppress the behavior using JavaScript, but since it is normal behavior for the browser, I wouldn't recommend doing so.
try this solution: replace the 'input' with 'button' and add attribute
type equals 'button' and handle the onclick event with submit javascript function
<form name='testForm'>
<input type='text' value="myName" />
<button type='button' onclick='testForm.submit()'/>
</form>
i think it works also with tag input adding the same attribute
Enjoy
Mirco
blur() is the way to go. It works like this:
<button onclick="this.blur();">some button</button>
Note that you should not use JavaScript and DOM-events using Attributes. This is just for demonstration purposes. Try to be unobstrusive.
Maybe it will help you out, the form is "supposed" to be sent with enter in the text box (HTML by design), it is no a matter of focus.
If you want to avoid it, check this out.
This is the proposed script:
function disableEnterKey(e)
{
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
return (key != 13);
}
Good luck, tell me if you need any clarification!
EDIT: I do agree with Piskvor answer, it may bring some bugs
this has nothing to do with the focus, its just the default behavior of you browser. to avoid this, you could try to cath the enter-keypress like this (Source - but there are a lot of other solutions (most working the same way, just using other events like the firms onsubmit instead of the documents onkeypress)):
function catchEnter(e){
// Catch IE’s window.event if the
// ‘e’ variable is null.
// FireFox and others populate the
// e variable automagically.
if (!e) e = window.event;
// Catch the keyCode into a variable.
// IE = keyCode, DOM = which.
var code = (e.keyCode) ? e.keyCode : e.which;
// If code = 13 (enter) or 3 (return),
// cancel it out; else keep going and
// process the key.
if (code == 13 || code == 3)
return false;
else
return true;
}
// Anonymous method to push the onkeypress
// onto the document.
// You could finegrain this by
// document.formName.onkeypress or even on a control.
window.onload = function() { document.onkeypress = catchEnter; };
Change:
<input type="text" ... >
To:
<textarea ... ></textarea>
You may need to mess around with the attributes a bit, I've left them signified as ....
try to add on the keypress event of your button this javascript function :
function ButtonKeyPress()
{
var code = (window.event.which) ? window.event.which : window.event.keyCode;
if ( code == 13 )
{
event.returnValue = false;
return false;
}
return true;
}
So, you have a form. In this form, you have a text input, and a submit button.
You get in the text input, you type some text, than you press "Enter". This submits the form.
You would like to break this normal behavior.
I think this is not a good idea : The convention says that when your in a text input and press "Enter", it submits the form. If you change this behavior, users could be (I don't find the right word, let's say ~) surprised.
Anyway, if you still want to do this, you should listen for the keypress event on the text input, and than prevent default behaviour shoud do the work.
let's say you use jQuery :
$(input[type=text]).bind('keypress', function(evt) {
if(evt.keyCode == 13) {
evt.preventDefault();
}
});
This should do it. I didn't test it, maybe I made mistakes, but you got the idea, no ?
And maybe keyup is better than keypress... I don't know very well this, not enough practice on key bindings
The easiest way is to set css style like this:
&:focus {
outline: 0 none;
}

Categories

Resources