How to change the behavior of Ctrl+Backspace - javascript

I'm trying to create a Brainfuck IDE with Electron JS. The text-editing part is a <textarea> HTML element.
Right now, when I press Ctrl+Backspace the entire script gets deleted because of what is considered a "word".
How can I change the behavior of Ctrl+Backspace? Is it a Chrome thing, or a JS/Electron thing, or an HTML thing, or a CSS thing?
I would like for each of the 8 Brainfuck characters to be treated as a word. With this behavior, a script that looks like this:
>>><<<+++---...,,,[[[]]]
would be completely deleted in 8 strokes of Ctrl+Backspace. Each block of 3 of the same character is a "word".

Just prevent the default behavior when a Ctrl+Backspace is pressed:
var ta = document.getElementById("ta");
ta.addEventListener("keydown", function(ev) { // when a keydown event happens in the textarea
if(ev.ctrlKey && ev.keyCode === 8) { // check if control key is pressed along with the backspace (key code 8)
ev.preventDefault(); // if so, prevent the default behavior of this event
}
});
<textarea id="ta"></textarea>
Note: After you prevent the default behavior, you can do whatever you like (add some text at the current cursor, delete some characters, ... anything you want).

Related

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

Ace Editor (javascript): Triggering a tab press event for Ace Editors event handlers (not just inserting '/t' or spaces)

I am using Ace Editor to build a code replay program. I store all the keys pressed when you type code, and then I replay them in Ace Editor. I have finished storing and replaying all keyboard/mouse input, but am having issues replaying tab presses.
Ace Editor handles tabs within a textarea DOM. The default behavior for a textarea when tab is pressed is to move to the next DOM, so I know they are using preventDefault() and using their own handler in order to allow softTab (insertion of 1,2,3, or 4 spaces before all highlighted text).
My goal is to cause Ace editor to trigger the tab event - such that whatever is currently highlighted in the Ace editor is tabbed over the correct number of spaces. Does anyone know how to do this?
Here are a list of options I've tried and why they don't work:
Store tab presses on keydown and then calculate the column value and insert the spaces in that location. BUT - this fails when you have some text half highlighted. The correct functionality should shift the entire word over, but this would just insert spaces in the middle of the word.
Store the location and keys pressed whenever editor.on('change', some_event_handler) fires, which gives me exactly what was input and the location (perfect for replay) except it doesnt tell me whether tab or spacebar was pressed (it will fire for both and spacebar is already handled). Plus this still inserts spaces at the location (potentially in middle of a word instead of shifting word over) as in number 1.
For example:
editor.getSession().on('change', function(e) {
if (handlers) {
var text = e.data.text;
if (text == ' ' || text == ' ' || text == ' ' || text == ' ') {
//FAILS because it doesn't know if its space or a single space tab.
Try to trick Ace Editor to trigger a tab by storing '/t' and inserting it into the ace Editor.
For example (storage code):
function keypress_handler(e) {
var key = e.which;
var text = String.fromCharCode(key);
switch(key) {
case 9: //Tab
text = '\t'; // manually add tab
//Code to store this event for replay later
break;
}
For example (replay code):
// Assuming the cursor/selection is in the correct position
editor.insert(log.text);
At this point, I was beginning to think about building tab from scratch (when to shift multiple things if multiple lines are selected, how far to shift, how to handle if a word is half highlighted when tab is pressed), but Ace clearly already does this when tab is pressed, so I would like to just trigger the tab press. Normally to trigger a tab press, I'd simply do:
// trigger an artificial Tab Keydown event for Ace Editor using jQuery
var tab_press= $.Event('keydown');
tab_press = 9; // Tab keycode
$('.editor').trigger(tab_press);
But this causes results in no behavior. Any suggestions?
I read through the source code here:
https://github.com/ajaxorg/ace/blob/master/lib/ace/commands/default_commands.js
And found the following snippet of code:
{
name: "indent",
bindKey: bindKey("Tab", "Tab"),
exec: function(editor) { editor.indent(); },
multiSelectAction: "forEach",
scrollIntoView: "selectionPart"
}
Thus, to trigger a tab (that works in all cases), simply call:
editor.indent();
How incredibly simple - wish there was some documentation out there for this so that many hours could have been spared.
In Ace all of the user input from keyboard is processed via commands. This is used in Ace to record and replay macros see https://github.com/ajaxorg/ace/blob/v1.1.4/lib/ace/commands/command_manager.js#L52-L96.
If you want to record user input and then to replay it you can use
// record
commands=[]
editor.commands.on("afterExec", function(e) {
commands.push({name: e.command.name, args: e.args})
});
// replay
commands.forEach(function(e) {editor.execCommand(e.name, e.args)})
Capturing mouse input is a bit tricker, but from question it seems you already know how to do it.
This pull request is somewhat related to your question. It allows to emulate user input by calling simulateKeys("a", "b", "ctrl-Left", "Tab")

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

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.

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