I need to implement the backspace key behaviour so that my cursor is placed one position to the left without the user pressing the Backspace key, but rather after a string is added programmatically inside my (contenteditable) div, I need the cursor to move automatically one position left. I tried adding \b to my string, with no success.
How can I achieve this behaviour (preferably using JavaScript)?
You can easily workaround this by injecting a browser event into your content editable. I am showing an example using the left arrow key because you wrote that you want to move the cursor, which I would expect is what you want, because Backspace would delete a character. If you want to delete then replace the keycode for left with backspace.
Here is how it's done using jQuery:
var ev = jQuery.Event("keydown"); // Creates a new keydown event
ev.keyCode = $.ui.keyCode.LEFT; // Sets the event keyCode to be the left arrow button
$('#contentEditableContainer').trigger(ev);
To include jQuery:
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
Here is the function that I use, make sure you include jQuery. Just call this function with a id to the text box you want the backspace to act:
function backSpace(id){
var txt = $(id);
var startPos = txt[0].selectionStart;
var endPos = txt[0].selectionEnd;
var scrollPos = txt[0].scrollTop;
console.log("start: " + startPos + " end: " + endPos + " scrollPos: " + scrollPos);
if (endPos - startPos > 0){
txt.val(txt.val().slice(0, startPos) + txt.val().slice(endPos, 100));
}else if (endPos > 0){
txt.val(txt.val().slice(0, startPos-1) + txt.val().slice(startPos, 100));
}else{
startPos = txt.val().length+1;
}
txt.focus();
txt[0].setSelectionRange(startPos-1,startPos-1);
}
Related
I created a textarea and a button. When the button is clicked, I want to add the letter 'a' at the current position of the cursor in the textarea. Below is my current code:
$('button.buttonA').click(function(){
var cursorPos = $('textarea.formInsideMenu').prop('selectionStart');
var textCurrent = $('textarea.formInsideMenu').val();
var textBefore = textCurrent.substring(0, cursorPos);
var textAfter = textCurrent.substring(cursorPos, textCurrent.length);
$('textarea.formInsideMenu').val(textBefore + 'a' + textAfter);
});
The above code works fine, (inserts an 'a' at the correct position), when the focus is on the textarea; but as soon as I click on the button, I lose focus of the textarea and the cursor is no longer showing. If I click on the button again after this, 'a' is appended at the very end of the text, (it seems like the cursor is moved to the end of the text). Is there anyway to keep track of where the cursor is inside the textarea even when something else has been clicked on and the textarea has lost focus?
Once you're done with the insert, you need to focus the textarea and set the caret position back:
$('button.buttonA').click(function() {
var area = $('textarea.formInsideMenu'),
curPos = area.prop('selectionEnd');// at the caret **or after selected text**
area.val( area.val().substring(0, curPos) + 'a' + area.val().substring(curPos) )
.focus()
.prop({'selectionStart': curPos+1, 'selectionEnd': curPos+1});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="buttonA">Add an a</button> <br>
<textarea class="formInsideMenu"></textarea>
This version uses javascript only after returning the dom object from jQuery:
$('button.buttonA').click(function(){
var text = $('textarea.formInsideMenu').get(0);
var start = text.selectionStart;
text.value = text.value.slice(0,start) + 'a' + text.value.slice(start);
text.setSelectionRange(start+1,start+1);
text.focus();
});
Fiddle here
Use setSelectionRange after inserting the 'a'.
$('button.buttonA').click(function(){
var cursorPos = $('textarea.formInsideMenu').prop('selectionStart');
var textCurrent = $('textarea.formInsideMenu').val();
var textBefore = textCurrent.substring(0, cursorPos);
var textAfter = textCurrent.substring(cursorPos, textCurrent.length);
$('textarea.formInsideMenu').val(textBefore + 'a' + textAfter);
var elem = document.getElementsByClassName("formInsideMenu")[0];
elem.setSelectionRange(cursorPos, cursorPos + 1);
});
https://jsfiddle.net/ny82n5kn/
You can make a change event on the textarea, where you sore the position of the cursor, like this:
var cursorPos;
$('textarea.formInsideMenu').on('change', function(){
cursorPos = $(this)).prop('selectionStart');
};
Now it will be avaiable in the clickhandler.
I have an input field where i append data at the cursor position.
after that, i set the selectionStart to the end of the field.
BUT, whenever i add something to the input (by button clicks), i only see the left part of it (until it reaches the right edge). everything more is there (i can select it with the mouse and scroll), but it doesn't automatically show the right edge.
how can i do that?
i want to add something to the input and jump right to the end of the string.
// add 2 digit number
$('button#2digit').on('click', function add2digit() {
addNumberToInput(10, 99);
});
function addNumberToInput(min, max) {
var problemInput = $('input#testProblem');
if (lastCharIsOperation() || problemInput.val().trim() < 1) { // if last char is an operation or first in string, just append the number
addAtCursor(randomNonPrime(min, max));
} else {
addAtCursor('+' + randomNonPrime(min, max));
}
}
function addAtCursor(toAdd) {
var problemInput = $('input#testProblem');
var oldText = problemInput.val();
var cursor = problemInput[0].selectionStart;
var pre = oldText.substring(0,cursor);
var post = oldText.substring(cursor, oldText.length);
//insert at cursor
problemInput.val(pre + toAdd + post);
//put cursor to end
problemInput[0].selectionStart = problemInput.val().length;
}
(it even skips back to the left on blur, i couldn't make a picture with the windows snipping tool, because i had to click it first)
From Set mouse focus and move cursor to end of input using jQuery.
var problemInput = $('input#testProblem');
problemInput.focus();
var t=problemInput.val();
problemInput.val('');
problemInput.val(t);
Here is the start of a full solution: https://jsfiddle.net/michaelgentry/vwm159pt/
This will still cause the scroll to jump back to the left on blur, but does what you are asking:
var elem = document.getElementById('myInput');
elem.focus();
elem.scrollLeft = elem.scrollWidth;
I have a form with a textarea (id = details).
Is there a way I can insert the HTML code for a line break (<br />) at the cursor position when hitting Enter within this textarea ?
I would only need this to get to work in IE.
<textarea class="input height120 elastic span12" name="details" id="details" onkeyup="countCharLimit(event)" onpaste="countCharLimit(event)"></textarea>
Try this:
$('textarea').keypress(function (e){
if(e.keyCode == 13){
$('textarea').val($('textarea').val()+"<br />");
}
});
You could try and fiddle with it here
EDIT: I realized this is adding a <br /> at the end only, after some more research, I found this solution:
$('textarea').keypress(function (e){
if(e.keyCode == 13){
e.preventDefault();
this.value = this.value.substring(0, this.selectionStart)+"<br />"+"\n";
}
});
Here is a fiddle for this one
Source (mostly): Insert text into textarea with jQuery
EDIT AGAIN: Looks like the OP wanted the text at the end to also be cleared, so I updated my code accordingly (for other's seeing this: check out the first edit of my relevant fiddle for the case you'd want to keep the remaining text).
you will need to find the caret position first as follow:
var caretPos = function() {
var el = $("#details").get(0);
var pos = 0;
if('selectionStart' in el) {
pos = el.selectionStart;
} else if('selection' in document) {
el.focus();
var Sel = document.selection.createRange();
var SelLength = document.selection.createRange().text.length;
Sel.moveStart('character', -el.value.length);
pos = Sel.text.length - SelLength;
}
return pos;
}
taken from :here
then you do:
var textofDetails = $("#details").val();
jQuery("#detail").val(textofDetails.substring(0, caretPos) + "<br/>" + textofDetails.substring(caretPos) );
Major EDIT:
no need for all the above ; your function will be
function replaceNewLine(){
jQuery("#detail").val().replace(/\\n/g, "<br />");
}
source: so - here
Yes, sure. It seems to be so, that you need keydown event processing and, possible, setTimeout 0 hack, look here: Why is setTimeout(fn, 0) sometimes useful?
I have a simple script showing the character count for a text input element or a textarea element.
$("input[type=text],textarea").keyup(function(){
var currentLength = ($(this).val().length);
var maximum = 100;
var spanLimit = $("span[name=Limit]");
spanLimit.html("("+ currentLength + " of " + maximum + ")");
});
While the script performs its function, I noticed that the user loses the ability to undo his/her typing with either Ctrl+Z or the right click menu option. If I comment out the following line, the undo function is not lost:
spanLimit.html("("+ currentLength + " of " + maximum + ")");
Is there any way to not lose the undo stack after performing DOM manipulation?
P.S. This behavior is visible when using IE8
You forgot a quote in var spanLimit = $("span[name=Limit]);.
It should be var spanLimit = $("span[name=Limit]");
I have this textarea that shows inputted text, but when the number of lines exceeds the size and width of the textarea, the user has to scroll down to see what they have last inputted.
I'd like the textarea to be set to the bottom everytime the enter button is pressed.
I've tried the following, but I can't get it to work:
function inputKeyDown(evt, input) {
if (evt.keyCode == 13) {
var textarea = document.getElementById("textarea");
textarea.value += "\n" + ">" + " " + input.value;
input.value = "";
return false;
}
var elem = document.getElementById('textarea');
elem.scrollTop = elem.scrollHeight;
}
and then I call the function keyDown in <input onKeyDown="return keyDown(event, this);" ...>
Any idea why no workie?
Try the following:
textarea.scrollTop = textarea.scrollHeight - textarea.clientHeight;
It depends on what sort of input you are looking at, but forcing the cursor back to the bottom could potentially be a serious usability problem. If you need a textarea that automatically expands, have a look at existing solutions such as this jQuery plugin
I'm not really sure if this is what you want but have a look this: http://jsfiddle.net/yV76p/
var textarea = document.getElementById("textarea");
textarea.onkeyup = function(evt) {
this.scrollTop = this.scrollHeight;
}