I'm making text editor.
This is demo image what i made
Using contenteditable, I render code to dangerouslySetInnerHTML.
So the component look like this
But like figure1, I can access next to select
( In second figure, it is between </div> here <select ~~>
I want to prevent a user from accessing and writing at that point
But I did not found preventing access method.
So I thought when user write content then check the parent and execute event.preventDefault() except for left arrow and up arrow.
it works well in English and others.
But when I write Korean. PreventDefault is not working.
How can I execute preventDefault in Korean??
handleKeyDown = (event) => {
let key;
if(window.event) {
key = event.keyCode;
} else {
key = event.which; //For Firefox
}
const selection = document.getSelection();
if (selection.anchorNode) {
const check = selection.anchorNode.parentElement;
if (check.className.includes('src-components') && key !==37 && key !== 38) {
event.preventDefault();
event.stopPropagation();
}
}
}
P.S : the event.target.value return undefined.
Related
I'm trying to prevent page scrolling on my custom dropdown search using StimulusJS. Much like in gmail, where you can type something in a search box and use arrow keys to navigate. I go to that point where I can navigate the dropdown, but at the same time default behaviour for arrow keys is problematic here.
// results are divs that get focused
const results = [node1, node2, node3]
if (this.listCounter <= -1) { this.listCounter = -1 }
if (this.listCounter >= results.length) { this.listCounter = results.length - 1 }
switch (event.key) {
case 'ArrowDown':
this.listCounter++
break
case 'ArrowUp':
this.listCounter--
// when we reach the top we focus back on input element
if (this.listCounter <= 0) {
this.userInputTarget.focus()
}
break
default:
break
}
if (results[this.listCounter]) {
results[this.listCounter].focus()
}
So this works well, but the problem is that pressing arrow keys up/down also invokes scroll on the page. So I tried disabling it, but only when the key is pressed. I don't want to disable this behaviour for the whole page, only when certain elements are focused. Below console.log() gets fired, but it doesn't stop the window from being scrolled.
connect() {
window.addEventListener('keyup', this.preventKeyboardEvents.bind(this), false)
}
preventKeyboardEvents(e) {
const key = e.key
const results = window.allMultisearchActiveElements
const activeElement = results.includes(document.activeElement) || document.activeElement === this.userInputTarget
if (activeElement && (key === "ArrowDown" || key === "ArrowUp" || key === "Enter")) {
e.preventDefault()
console.log('fired')
}
}
Which part of it am I getting wrong? Is it even possible to .preventDefault() only for certain events?
Comes out it was rather simple.
window.addEventListener('keydown', this.preventKeyboardEvents.bind(this), false)
Since when pressing a key keydown event is fired first, I assume it fires a default behaviour of scrolling in the browser window. So using keyup was a problem here, because it was fired after the window has received the event from keydown.
How to repeat behaviour CMD+arrowLeft (Home) and CMD+arrowRight (End) for fn+arrowLeft and fn+arrowRight as well.
Please write code if existed another approach to move caret (cursor) to the begin or to the end of input field use combination of keys. I use MacOs.
36 - event.key for fn+arrowLeft
35 - event.key for fn+arrowRight
const handleKey = (e) => {
if (e.metaKey || e.altKey || e.ctrlKey) {
e.preventDefault();
}
if (e.key === 'Home') {
// code here
}
if (e.key === 'End') {
// code here
}
};
<input type="text" onkeydown="handleKey()">
As alternative way but doesn’t cover my need:
Set keyboard caret position in html textbox
I assumed that good way but don’t know how use right KeyboardEvent object:
how to set keycode value while triggering keypress event manually in pure javascript?
I have two functions that have if statements inside them. I am trying to choose which function to run based off which keys are pressed. When ran the keys without shift override the shift if statements. I am sure to solve this an event handler should be used. However I am not sure where to even start. If the standard ifs are taken out the shift if statements work and vice versa.
Individually each function works as intended. I have looked into adding an event handler based off what is pressed which function overrides which. I have looked at Event Handing and not really sure where to begin.
var map = {};
onkeydown = onkeyup = function(e){
e = e || event; //deals with IE Compatibility
map[e.key] = e.type == 'keydown';
}
I have an array that maps the keys that are pressed since there are more than one key that can be pressed at a specific time.
document.onkeydown = function (e){
if(e.which == 16 && e.which == 117){ //ShiftF6
try {
document.querySelectorAll("input[value=Close]")[0].click();
console.log("Button clicked.");
} catch(ex) {
};
try {
// eslint-disable-line prefer-template
document.querySelectorAll("textarea[name=bugnote_text]")[0].value = //display text
document.querySelectorAll("input[value='Close Ticket']")[0].click();
console.log("Button clicked.");
} catch(ex) {
};
}
This is an example of what is being done with shift and a simple function key.
document.onkeydown = function(zEvent){
if(zEvent.which == 117){ //F6
try {
document.querySelectorAll("input[value=Close]")[0].click();
console.log("Button clicked.");
} catch(ex) {
};
try {
// eslint-disable-line prefer-template
document.querySelectorAll("textarea[name=bugnote_text]")[0].value = //Display text;
document.querySelectorAll("input[value='Close Ticket']")[0].click();
console.log("Button clicked.");
} catch(ex) {
};
}
This is just a single button press.
Note there are multiple if statements inside each function no more than 5 in each however. I know placing these statements in a switch or array would probably be cleaner. I am trying to just decide which function to work out of depending which buttons are being pressed. I am not sure where to begin to get it to choose which way to go.
How can I clarify ALT+CTRL and ALTGR key press?
I found this code here as possible solution, but it's doesn't work:
if (event.ctrlKey && event.altKey) {
}
This code is true for alt+ctr and for altGr as well.
I have situation like this: for alt+ctrl+e (for example e, it's no matter) I want one thing and for altGr+e another, how can I do this?
If anyone have some idea, please tell me.
You can detect which key is pressed (from right key or left key) by value of location property in event object. If value of location property is 1 (e.location=1) then left key is pressed. if value is 2 then right key is pressed.
Here I have providing my code for RightAlter+RightCtrl+<any_valid_key>
Check this Example
var isRightAltKey=false;
var isRightCtrlKey=false;
var validKeys=['a','s','d','f','g']; //keep empty array if no need to check key
document.addEventListener("keydown", function(e) {
if(e.key=="Alt"){
// when right Alter pressed make isRightAltKey true
isRightAltKey= (e.location==2);
}
else if(e.key=="Control"){
// when right Control pressed make isRightCtrlKey true,
//if you need any ctrl key pressed then simply set isRightCtrlKey= true;
isRightCtrlKey= (e.location==2);
}
// checking both right key is pressed already or not?
var isRightKeys= isRightAltKey && isRightCtrlKey;
// validate other keys [optional]
var isValidKey=((typeof validKeys === "undefined") || validKeys.length==0 || validKeys.indexOf(e.key.toLowerCase())>=0);
if (isRightKeys && isValidKey){
document.getElementById("detect_key").innerHTML = "RightAlt + RightCtrl + "+e.key;
}
else
{
document.getElementById("detect_key").innerHTML="";
}
}, false);
document.addEventListener("keyup", function(e) {
if(e.key=="Alt"){
// when right Alter released make isRightAltKey false
isRightAltKey= false;
}
else if(e.key=="Control"){
// when right Control released make isRightCtrlKey false
isRightCtrlKey= false;
}
}, false);
<div id="detect_key"></div>
Why attached keyup event listner?
Here we have to detect key location when Ctrl and Alt key is pressed (on keydown event). and we have to store it in flag variable and make it true. when key is released (on keyup event) have to mark as false. Otherwise those flags always remain true. on Next key press it will always true
You can use the location to determined which alt is being pressed.
In order to support Alt+Ctrl we'll save the last location of the pressed Alt.
Location = 1 // Left
Location = 2 // Right
Then, once both Alt and Ctrl are pressed, do your thing. In this example, we'll just write the Alt side in the result div. You can add the "e" pressed condition as well:
if (e.ctrlKey && e.altKey && e.key == "e"){
Example
HTML
<div class="cont">
Click Alt + Ctrl<br /><br />
<div id="res"></div>
</div>
Javascript
var lastAltLocation;
document.addEventListener("keydown", function(e) {
if (e.key == "Alt"){
lastAltLocation = e.location;
}
if (e.ctrlKey && e.altKey){
if (lastAltLocation == 1){
document.getElementById("res").innerHTML = "Left";
}
if (lastAltLocation == 2){
document.getElementById("res").innerHTML = "Right";
}
}
}, false);
Sticking strictly to your question here are the codes for both the required cases:
document.addEventListener ("keydown", function (zEvent) {
if (zEvent.altKey && zEvent.code === "KeyE") {
if(zEvent.ctrlKey) {
//Do Ctrl+Alt+E Stuff Here.
} else {
//Do Alt+E Stuff Here.
}
});
Now breaking down the things going on here. keydown allows you to detect multiple keypresses.
First we check if the Alt and E keys are pressed. If yes, we then go on to check in the Ctrl key is also active and take the appropriate action as needed.
I have a huge entry form and fields for the users to input.
In the form user use tab key to move to next feild,there are some hidden fields and readonly textboxes in between on which tab key is disabled using javascript.
Now users finds difficult to use tab key and wants same functionality on down arrow key of the keyboard.
I was using the below code to invoke the tab key code on js but not working,please some body help me on this.
function handleKeyDownEvent(eventRef)
{
var charCode = (window.event) ? eventRef.keyCode : eventRef.which;
//alert(charCode);
// Arrow keys (37:left, 38:up, 39:right, 40:down)...
if ( (charCode == 40) )
{
if ( window.event )
window.event.keyCode = 9;
else
event.which = 9;
return false;
}
return true;
}
<input type="text" onkeydown=" return handleKeyDownEvent(event);" >
Using jQuery, you can do this :
$('input, select').keydown(function(e) {
if (e.keyCode==40) {
$(this).next('input, select').focus();
}
});
When you press the down arrow key (keyCode 40), the next input receives the focus.
DEMO
EDIT :
In Vanilla JS, this could be done like this :
function doThing(inputs) {
for (var i=0; i<inputs.length; i++) {
inputs[i].onkeydown = function(e) {
if (e.keyCode==40) {
var node = this.nextSibling;
while (node) {
console.log(node.tagName);
if (node.tagName=='INPUT' || node.tagName=='SELECT') {
node.focus();
break;
}
node = node.nextSibling;
}
}
};
};
}
doThing(document.getElementsByTagName('input'));
doThing(document.getElementsByTagName('select'));
Note that you'd probably want to map the up key too, and go to first input at last one, etc. I let you handle the details depending on your exact requirements.
This is my final working code:
$('input[type="text"],textarea').keydown( function(e) {
var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
if(key == 40) {
e.preventDefault();
var inputs = $(this).parents('form').find(':input[type="text"]:enabled:visible:not("disabled"),textarea');
inputs.eq( inputs.index(this)+ 1 ).focus();
inputs.eq( inputs.index(this)+ 1 ).click();
}
});
If I understand correctly, some fields are read-only, so the tab key still activates them, even though they are read-only, and this is annoying, as you have to press the tab key perhaps several times to get to the next editable field. If that is correct, then an alternate solution would be to use the tabindex attribute on your input fields, indexing each one so that the read-only and otherwise non-editable fields aren't selected. You can find more info on the tabindex attribute here.