ryanpika February 2016

How to set the default cursor caret in the middle of textarea/input vertically when on focus

I wondered how to use javascript/css to set the default cursor position in between of the two lines of placeholder text, so the user input could be vertically centered in the input field (which looks better I think).

Demo below

<textarea id="topic_title_input" placeholder="Hi there, I want the cursor caret starts in the middle of these two lines (veritcally) when onfocus"></textarea>



<style>
#topic_title_input{
    font-size: 20;
    border-color: orange;
    color:black;
    background-color: white;
    /*text-indent:10px;*/
    border:1px solid orange;
    width:521px;
    height:60px;
    outline:none;
    border-radius:3px;
    resize:none;
    padding:7px;
}
</style>

Answers


Will February 2016

Not quite sure I get what you're asking but it was fun anyway. This presumes you want to actually use the placeholder text and insert the caret in the middle. Second is an attempt to discern what you meant by 'vertical'.

var input = document.getElementById('topic_title_input');
var inputSpace = document.getElementById('topic_title_alt');

// Proof of concept. Will blow out existing text on each focus!
input.addEventListener('focus', updateTextArea);
inputSpace.addEventListener('focus', withBreak);

function updateTextArea(e) {
  var value, pos;

  value = input.getAttribute('placeholder');
  // Put it anywhere you want
  pos = value.indexOf('middle');
  input.value = value;
  // Normal browsers and IE9+:
  input.setSelectionRange(pos, pos);
}


function withBreak(e) {
  var value, pos, splitVal, newVal;

  value = inputSpace.getAttribute('placeholder');
  // Put it anywhere you want
  pos = value.indexOf('middle');

  newVal = value.substring(0, pos) + "\r\n\r\n";
  newVal += value.substring(pos)

  inputSpace.value = newVal;
  // Normal browsers and IE9+:
  inputSpace.setSelectionRange(pos + 1, pos + 1);
}
textarea {
  font-size: 20;
  border-color: orange;
  color: black;
  background-color: white;
  /*text-indent:10px;*/
  border: 1px solid orange;
  width: 521px;
  height: 60px;
  outline: none;
  border-radius: 3px;
  resize: none;
  padding: 7px;
}
<h2>Insert at "middle"</h2>
<textarea id="topic_title_input" placeholder="Hi there, I want the cursor caret starts in the middle of these two lines (veritcally) when onfocus"></textarea>

<h2>This kind of space?</h2>
 

Post Status

Asked in February 2016
Viewed 1,346 times
Voted 5
Answered 1 times

Search




Leave an answer