-
Editable dom element에 focus를 할때 cursor로 끝으로 옮기는 법Web Dev/8. 메모 2021. 5. 30. 16:53728x90
// 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 } };
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}`); } };
'Web Dev > 8. 메모' 카테고리의 다른 글
Json에서 Type 바로뽑아주는 사이트 (0) 2021.06.02 Tailwind css로 초간단 Dropdown 메뉴 구성하기 (0) 2021.06.02 HTMLElement에 contentEditable 속성을 줘서, 편집가능하도록 만들기 (0) 2021.05.27 Appending parameter to URL without refresh (0) 2021.05.27 JWT 란? (0) 2021.03.05