JAVASCRIPT

자바스크립트 도움되는 정보 1

 

  1. querySelectorAll(), e.preventDefault(), e.stopPropagation()
  2. How to get selected word when double-click on div, p, span?

 


 

 1. querySelectorAll(), e.preventDefault(), e.stopPropagation()

 

https://stackoverflow.com/questions/34522988/attaching-a-click-event-to-multiple-elements-at-once

 

var elements = document.querySelectorAll(“a, div, img”);
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener(“click”, function(e) {
console.log(“clicked”);
e.preventDefault(); // a 태그의 href 기능을 막음
e.stopPropagation(); // 상위 클릭이벤트를 막음, 현재 클릭이벤트는 막지 않음
});
};

 

 


 

2. How to get selected word when double-click on div, p, span?

 

// document.selection.createRange().text in IE
// window.getSelection().toString() in firefox and webkit

document.ondblclick = function () {
   var sel = (document.selection && document.selection.createRange().text) ||
             (window.getSelection && window.getSelection().toString());
   alert(sel);
};

 

// anchorNode : 선택이 시작된 노드
// baseOffset : 시작 위치
// extentOffset : 끝 위치

<p>test data.</p>

<script>
  document.addEventListener("dblclick", (e)=>{
    const selection = document.getSelection()
    // console.log(selection.anchorNode.data) // is whole text: "test data."
    const selectContent = selection.anchorNode.data.slice(selection.baseOffset, selection.extentOffset)
    console.log(selectContent)    
  })
</script>

 

https://stackoverflow.com/questions/2281426/how-to-get-selected-word-when-double-click-on-div-p-span

 

 


 

 

Related posts

Leave a Comment