0

Suppose I have a div that contains a sentence such as the one listed below:

<div class="sentence">This is a sentence</div>

I am trying to create a function/event handler that will recognize when the user clicks on the text inside the <div>. But, when they click inside the <div> the function needs to know exactly where they clicked so I can insert a <span> at that location. For example, if the user clicks in between the letters 'n' and 't' in the word 'sentence', then I want to insert a <span> there so I end up with

<div class="sentence">This is a sen<span>test</span>tence</div>

Something like this:

$('.sentence').on('click', function (e) {
    var to_insert = '<span>test</span>';
    // determine exactly where inside the div I clicked
    // insert 'to_insert' at that location
});

Any ideas?

Chris Paterson
  • 193
  • 2
  • 11
  • 3
    Take a look at this question http://stackoverflow.com/questions/7563169/detect-which-word-has-been-clicked-on-within-a-text – bhspencer Sep 01 '15 at 23:13
  • The linked question above assumes the user has selected a word. My requirement is that the user has just simply clicked their mouse somewhere on a word, not selected it. – Chris Paterson Sep 02 '15 at 01:46
  • It is essentially the same problem. – bhspencer Sep 02 '15 at 02:15
  • window.getSelection(); returns a Selection object representing the range of text selected by the user or the current position of the caret. You can use that figure out where in the text the click is and then recreate the text with the span. – bhspencer Sep 02 '15 at 02:18

1 Answers1

2

You can to get the position of the click in a string, using window.getSelection().anchorOffset

JS

$('.sentence').on('click', function (e) {
    var to_insert = 'test';
    var anchorOffset = window.getSelection().anchorOffset;
    var resultHtml = $(this).html().substring(0, anchorOffset) + to_insert + $(this).html().substring(anchorOffset);
    $(this).html(resultHtml);
});

DEMO

bhspencer
  • 13,086
  • 5
  • 35
  • 44
J Santosh
  • 3,808
  • 2
  • 22
  • 43