Web Dev/8. 메모

Editable dom element에 focus를 할때 cursor로 끝으로 옮기는 법

hYhY1234 2021. 5. 30. 16:53
728x90
// ref: https://stackoverflow.com/questions/1125292/how-to-move-cursor-to-end-of-contenteditable-entity/3866442#3866442
export const setEndOfContenteditable = (contentEditableElement) => {
  var range, selection;
  if (document.createRange) {
    //Firefox, Chrome, Opera, Safari, IE 9+
    range = document.createRange(); //Create a range (a range is a like the selection but invisible)
    range.selectNodeContents(contentEditableElement); //Select the entire contents of the element with the range
    range.collapse(false); //collapse the range to the end point. false means collapse to end rather than the start
    selection = window.getSelection(); //get the selection object (allows you to change selection)
    selection.removeAllRanges(); //remove any selections already made
    selection.addRange(range); //make the range you have just created the visible selection
  } else if (document.selection) {
    //IE 8 and lower
    range = document.body.createTextRange(); //Create a range (a range is a like the selection but invisible)
    range.moveToElementText(contentEditableElement); //Select the entire contents of the element with the range
    range.collapse(false); //collapse the range to the end point. false means collapse to end rather than the start
    range.select(); //Select the range (make it the visible selection
  }
};

ref: https://stackoverflow.com/questions/1125292/how-to-move-cursor-to-end-of-contenteditable-entity/3866442#3866442

 

Editable객체를 focusing을 할때 끝에 위의 코드를 사용하면 끝에 focusing 이 된다. react에서 useRef를 통해서 dom에 접근하고 있을때 아래와 같이 사용가능하다.

 

export const focusTargetDomElement = (target) => {
  try {
    target.firstChild.firstChild.focus();
    setEndOfContenteditable(target.firstChild.firstChild); // 해당 dom element를 넘겨만 주면된다
  } catch (e) {
    console.error(`focusing error: ${e.message}`);
  }
};