Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the text that was clicked on in Javascript?

Tags:

javascript

Does anyone know if it is possible with javascript to to tell the position of a mouse click in some text? I know it's easy to get the x,y coordinates, but I'm wanting the position in the text.

For example if I clicked inside <p>foo bar</p> I want to be able to tell that the click was on/after the 5th character. Or that foo b is before the click and ar is after it.

By the way, I'm using jQuery too, I'm happy with pure JS and solutions that use jQ.

Thanks in advance.

like image 740
Jake Avatar asked Feb 02 '26 04:02

Jake


2 Answers

Javascript and browsers don't support this directly, but you could technically wrap each character in a span and do it based on which span was clicked on:

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

If anybody actually tries this, be prepared to be eaten by a velociraptor :p

like image 53
Dean Harding Avatar answered Feb 03 '26 17:02

Dean Harding


Expanding on codeka's answer and my comment . . . try this (i'm assuming your target p has 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) + '"');
    }
  });
})();

What that does is: 1. Find the paragraph where you need per-character clicking knowledge, 2. Split the text in that paragraph into a number of one-character spans, 3. Inform each of those one-character spans of its position in the string, and 4. Assign a click() handler to each span, which spits out the information about the span (including your example of char index >= 5, and printing the before and after parts of the string).

Of course you might want to put that in $(document).ready(...) instead of an anonymous function; I didn't know if maybe you had a precondition for activating this detection though.

like image 31
Walt W Avatar answered Feb 03 '26 18:02

Walt W