Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Split text at mouse-click position

I'm trying to program something like a textarea, just for training.

I have a div with (user-generated) text in it:

<div id="editor">Hello! I am a Text!</div>

If I click (with left mousebutton) between the two "L" of "Hello", for example, I'd like to see this:

<div id="editor">Hel<div id="cursor">|</div>lo! I am a Text!</div>

How do I achieve this? Until now, I'm doing it with...

//HTML
<div id="editor" onclick="setCursorWithMouse()"><!-- User-Text --></div>

//jQuery
function setCursorWithMouse(){
    $('#editor').append('<div id="cursor">|</div>');
}

...but, of course, it just adds the cursor at the end of the div.

How can I know where exactly the user clicked, where to add my cursor (or whatever), where to split the text?

Thanks

Edit:

  • I do not want to use contenteditable! Just look at it this way: I want to split a string at the mouse-click position.

  • I know .append() is not what I'm looking for! .append() was just a Placeholder for a later, better, function. THIS function I'm right now asking for.

  • I use a fixed-width font.

like image 833
WcPc Avatar asked Sep 06 '14 14:09

WcPc


1 Answers

this is as close as I could get: DEMO

var clicked=false;
$('#editor').click(function(e){
    $(this).addClass('active');
    var letterWidth=7;
    $('#editor span').remove();
    var clickPos=e.pageX-$(this).offset().left;
    if(!clicked) clickPos+letterWidth;
    var letter=Math.round(clickPos/letterWidth);
    var before=$(this).html().substr(0,letter);
    var after=$(this).html().substr(letter,$(this).html().length);
    $(this).html(before+'<span>|</span>'+after);
    clicked=true;
});
$(document).click(function(e){
    if(!$('#editor').is(e.target)){
        $('#editor').removeClass('active');
        $('#editor span').remove();
        clicked=false;
    }
});

I hope it's close enough! :)

NOTE:

this code is written assuming that the font-size is 16px!

I'm afraid you have to calculate the font-size for further expansions.

like image 87
Amin Jafari Avatar answered Oct 15 '22 18:10

Amin Jafari