0

I need to insert image between the text where mouse click occurs such that the image inserts itself between the text and not overlap the text as can be seen in this jsfilddle.

$('#box').click(function(ev){
    $('img.mover').clone()
    .removeClass('mover')
    .appendTo('body')

    .css('left', ev.pageX-20)
    .css('top', ev.pageY-20);
 });

After the change basically it should look like mbmnB/img/Nmnbbmn if I click between B and N.

Nikhil Kumar
  • 114
  • 7

3 Answers3

1

You can convert the text into nodes (span) and then detect the mouse click event on the nodes. Than split the text from that node and insert your image in between :

To convert in text node :

function wrapCharacters(element) {
            $(element).contents().each(function() {
                if(this.nodeType === 1) {
                    wrapCharacters(this);
                }
                else if(this.nodeType === 3) {
                    $(this).replaceWith($.map(this.nodeValue.split(''), function(c) {
                       return '<span>' + c + '</span>';
                    }).join(''));
                }
            });
        }    


        wrapCharacters($('#box')[0]);

check this fiddle hope it helps:

Fiddle

Ankit Tyagi
  • 2,381
  • 10
  • 19
0

Put every single letter into a span so that you can detect over which one the mouse is when the click event happens.

donkeydown
  • 698
  • 7
  • 16
0

You should split your text in two inline parts. So best it would be to use span elements as they are inline and do not introduce newlines.

Later on you should get caret position. You can use this answer to get it: get caret position. Lets say you have your position inside var pos;

Then you can split:

function span(text) {
  return '<span>'+text+'</span>';
}

var content = $('#box').html();
var left  = span(content.substring(0, pos));
var right = span(content.substring(pos, content.length));
var img   = '<img src="your_image.ext"></img>';
$('#box').html(left + img + right);

Note that this code is not tested but just displayes the mechanics.

Community
  • 1
  • 1
lukas.pukenis
  • 13,057
  • 12
  • 47
  • 81