How to get text that was clicked in Javascript?

Does anyone know if it is possible to use javascript to indicate the position of the mouse click in some text? I know that it is easy to get the x, y coordinates, but I want the position to be in the text.

For example, if I clicked inside <p>foo bar</p> I want to say that the click was enabled / after the 5th character. Or, foo bbefore the click and arafter it.

By the way, I also use jQuery, I am satisfied with pure JS and solutions using jQ.

Thanks in advance.

+3
source share
3 answers

Javascript and browsers do not support this directly, but you can technically wrap each character in a space and do it based on what space has been clicked:

<p>
    <span>f</span>
    <span>o</span>
    <span>o</span>
    <span> </span>
    <span>b</span>
    <span>a</span>
    <span>r</span>
</p>

- , , : p

+1

., ( , p id my_p):

(function() {
  var p = $('#my_p');
  var o_string = p.text();
  p.html('<span>' + o_string.split('').join('</span><span>') + '</span>');

  $('span', p).each(function(i) {
    $(this).data('MyIndex', i);
  }).click(function() {
    var char_index = $(this).data('MyIndex');
    if (char_index >= 5) {
      alert('You clicked after character 5!  Before: "' + o_string.substring(0, char_index) + '", After (inclusive): "' + o_string.substring(char_index) + '"');
    }
  });
})();

: 1. , , 2. , 3. 4 click() , ( char index >= 5 ).

, $(document).ready(...) ; , , .

+1

Frankly, I do not really like the idea of ​​tracing text and its scope. But I'm not quite sure what you are looking for, if you just need to click a word and make dblclick, rather than click, I will have the following code:

$('*').dblclick(function(event){
    console.log((window.getSelection() || document.getSelection() || document.selection.createRange().text).toString());
    event.stopPropagation();
});

after that you can deselect the text if you wish. Without toString (), you will get an object with many properties, examine it as well.

0
source

Source: https://habr.com/ru/post/1739248/


All Articles