Hello. Tell me how to get the text selection? There is a function containing this code:

if (window.getSelection) { return window.getSelection(); } else if (document.getSelection) { return document.getSelection(); } else if (document.selection) { return document.selection.createRange().text; } else { return 0 }; 

It is called by clicking on the desired link, but returns nothing. The console did not give any errors. As it seems to me, the problem is that after clicking on the link, all the selected text is “reset” and only then my function starts. How to solve a similar problem?

    4 answers 4

    Most likely, in any way, because clicking on any DOM-element leads to an automatic transfer of focus to the "clicked" element, thereby completely removing the previous input focus. Select a text - this is, in fact, the exact same focus.


    I’m sure about this exactly about the click, i.e. the "onClick" event, which I can’t say about "onMouseDown" . I advise you to handle not a click, but a mouse click down, that is, the "onMouseDown" event. This event does not remove the input focus ... but (!) "onMouseUp" click the mouse downwards, a release is supposed, that is, the subsequent "onMouseUp" event, which in total will generate "onClick" , and finally, which will remove the focus from the text. . It seems to me that a race condition may appear here ...

    • one
      Maybe you should try on the onmouseup event in the body of the body page to save the selected text in a special variable. Well, respectively, when you click on the link, take the value from the variable. - Pavel Vershinin
    • @Pavel Vershinin, in the sense of "onMouseDown ()"? - Salivan
    • one
      @Asen No, no, it was during onmouseup that is when the user finished dragging the selection with the mouse and released the left key. - Pavel Vershinin
    • 2
      onblur Vershinin, the idea is good, only it is more correct to use the onblur event on the text element. @Asen, do not talk nonsense. What is the condition of the race? JavaScript runs in one thread. - Ilya Pirogov
    • one
      I beg your pardon, I lied. onblur will not work, you need to use a special onselect event. An example . - Ilya Pirogov

    I know that quite a lot of time has passed since the question was created, but if I correctly understood the question, then the answer can be found here: Selection: Range, TextRange and Selection

      Hello! I had such a problem in ios safari, I decided through the function preventDefault - which cancels the standard actions and we can call our functions:

       function preventDef(event) { event.preventDefault(); getSel();//наша функция } function addHandler() {//вешаем на элемент document.getElementById("clickId").addEventListener("click", preventDef, false); } 

        Prefer onMouseOver . Here is:

        here is the first text that you need to select, get into a variable and display separately

        here is the second text, which you need to select, get into a variable and display separately

        here is the third text that you need to select, get into a variable and display separately

        here is the fourth text, which you need to select, get into a variable and display separately

        here is the fifth text, which you need to select, get into a variable and display separately

         <script> //получение выделенного текста с помощью анонимной самовызывающейся функции function get_text() { //объявление переменной var text; if(window.getSelection) { //современный способ text=window.getSelection().toString(); } else if (document.getSelection) { //старый способ text=document.getSelection(); } else if(document.selection) { //IE text=document.selection.createRange().text; } //вывод результата, если получен выделенный текст if(text){alert(text)}; } //применять эту функцию к тегам, содержащим текстовую информацию var p_arr=document.getElementsByTagName("p"); for(var i=0; i<p_arr.length; i++) { p_arr[i].onmouseup=get_text; } </script>