Issue
I'm making the same functionality which a command line has. When you enter some commands and then press the key up button, you will be presented with your previous command.
Now I have all that working and it works fine but I've encountered one small problem.
The problem I encounter now is that when pressing the up
key, the cursor is placed at the beginning of the command, while when using the down
button, the cursor is placed at the end of the comand.
Expected behaviour is that the cursor will be placed at the end for both.
What makes this different from other questions?
- The focus is already on the input field.
- It does work with the down button
setTimeout(function() {
var inputs = document.querySelectorAll('input');
inputs[0].onkeydown = function(e){
//keyup
if(e.keyCode == 38) {
inputs[inputs.length-1].value = 'up pressed';
}
if(e.keyCode == 40 ) {
inputs[0].value = 'down pressed';
}
}
}, 1000);
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<input type="text" placeholder="press the up or down key"/>
</body>
</html>
Solution
setTimeout(function() {
var inputs = document.querySelectorAll('input');
inputs[0].onkeydown = function(e){
//keyup
if(e.keyCode == 38) {
// placed here, it prevents the key's default behaviour to go at the end of the input text
e.preventDefault();
inputs[inputs.length-1].value = 'up pressed';
}
if(e.keyCode == 40 ) {
inputs[0].value = 'down pressed';
}
}
}, 1000);
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<input type="text" placeholder="press the up or down key"/>
</body>
</html>
Answered By - Vega
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.