javascriptonselect

How can I know when the user selects a paragraph?


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!


Solution

  • 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.