skip to Main Content

I am trying to implement a behavior where when selection is made by the user from the options list, after filling the the input box with the selected text the cursor pointer stays at the end of the text entered. The only constrain I have is I am unable to pass event object. So I cannot use event.currentTarget.value.length or something similar. I only have the option to call document.getElementByID or any of the other properties. But the text value that will be filled has dynamic classNames. Currently, I use Id name of the input box but that causes the cursor pointer to focus at the beginning of the text.
enter image description here

The code that I have used is:

document.getElementById('tags-container').focus();

The DOM structure of the input text is as follows:
enter image description here

Ideally I should use tc-tag-1 id so that the focus is after the text but that id is dynamically created. As I keep adding more selection, the tc-tag number keeps increasing. So I want to keep the cursor pointer at the last text entered. Is there any other attribute that I can use ? Is there any other way I can do without using event object.

2

Answers


  1. I am not sure to implement it in your input box with div element. But I will give an example of a set cursor at the end of the text with input element using setSelectionRage. (reference)

    document.getElementById('tags-container').onfocus = function(e) {
      let element = e.target;
      let targetCursor = element.value.length;
      setTimeout(function(){
        element.setSelectionRange(targetCursor, targetCursor);
      }, 1);
    }
    <input id="tags-container" type="text" />
    Login or Signup to reply.
  2. Use Selection.modify

    document.querySelector('button').addEventListener('click', function () {
      document.querySelector('input').focus()
      window.getSelection().modify('move', 'right', 'paragraph')
    })
    <input value="Lorem"/>
    <button>Put cursor at the end</button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search