0

I want to perform an action when the user selects any text at the page. I tried something like this:

 var selObj;

       document.querySelector("p").onselect = function(){
       selObj = window.getSelection(); 
       var selectedText = selObj.toString();
       //action

But then I discovered that onselect is only for inputs and text areas, and found no other way of trying something like this.

EDIT:I know how to get the selected text, I need an event that is triggered when the text is selected!

isherwood
  • 58,414
  • 16
  • 114
  • 157
Mr Guliarte
  • 739
  • 1
  • 10
  • 27

2 Answers2

0

You can bind a mouseup event to the paragraph("p") tag. Within that event handler, you can check:

document.selection.createRange().text

or

window.getSelection()

Also, you can check here javascript to get paragraph of selected text in web page.

Community
  • 1
  • 1
Akshat
  • 479
  • 4
  • 9
0

Use mouse events to capture the selection.

var paras = document.getElementsByClassName("para");

for (var i = 0; i < paras.length; i++) {
  paras[i].addEventListener('click', getSelected, false);
}

function selectElementContents(el) {

  return document.getSelection()||window.getSelection();

}

function getSelected() {

  var el = document.getElementById("selectedPara");
  alert(selectElementContents(el));

};
<p class="para">select me</p>
<p class="para">over me</p>
<p class="para">hey here</p>
roshan
  • 2,410
  • 2
  • 25
  • 37