Lauren Richardson
Lauren Richardson

Reputation: 1

Editable text inside span tags & place cursor at the end (Javascript)

I want a feature where clicking the Edit button will make the text content inside span tags editable. I was able to do that but couldn't figure out how to get the blinking cursor at the end of text.

Below is the simplified version of my code.

document.querySelector('button').addEventListener('click', function(){
  const span=document.querySelector('span');
  span.setAttribute('contentEditable', 'true');
  span.focus();
  let val=span.innerText;
  span.innerText='';
  span.innerText=val
})
<span>this is the span tag</span> <button>Edit</button>

Upvotes: 0

Views: 853

Answers (1)

dale landry
dale landry

Reputation: 8600

Create a new range object set the node you wish to set the range selection to addRange using getSelection... See notes in code snippit

https://developer.mozilla.org/en-US/docs/Web/API/Document/createRange

https://developer.mozilla.org/en-US/docs/Web/API/Window/getSelection

https://developer.mozilla.org/en-US/docs/Web/API/Range/selectNodeContents

https://developer.mozilla.org/en-US/docs/Web/API/Selection/removeAllRanges

document.querySelector('button').addEventListener('click', function() {
  const span = document.querySelector('span');
  span.setAttribute('contentEditable', 'true');
  span.focus();
  let val = span.innerHtml;
  span.innerHtml = '';
  span.innerHtml = val;
  
  //set a new range object
  let caret = document.createRange();
  //return the text selected or that will be appended to eventually
  let sel = window.getSelection();
  
  //get the node you wish to set range to
  caret.selectNodeContents(span);
  //set collapse to null or false to set at end of node
  caret.collapse(null);
  //make sure all ranges are removed from the selection object
  sel.removeAllRanges();
  //set all ranges to null and append it to the new range object
  sel.addRange(caret);
})
<span>this is the span tag</span> <button>Edit</button>

*This post may also be helpful to you...

How to set caret(cursor) position in contenteditable element (div)?

Upvotes: 2

Related Questions