onlineracoon
onlineracoon

Reputation: 2970

javascript, jquery insert element when clicked inside text

I'm trying to create a script that inserts an element when clicked inside an element that contains text.

Take a look at the picture below.

example

The A and B are mouse click positions of the end user.

So if the user would click on point A, the script has to insert an element between the lines where the click occured.

If the script would insert an element with a red background color, the result has to be like in the image below.

result

I honestly have no idea where to start, I found some WYSIWYG editors that use scripts to insert something at the carret position, but this is the cursor position and between 2 lines or at the end of a line. I really appreciate your help.

http://cdpn.io/nocfe

Upvotes: 0

Views: 77

Answers (1)

mgoeppner
mgoeppner

Reputation: 151

Assuming your markup is something like this:

<div class="text">
    <p>Thomas is rich...</p>
    <p>in the past...</p>
</div>

You could use $.after() to insert the new element

$(".text p").click(function()
{
    $(this).after("<p>I'm the new element</p>");
});

Upvotes: 1

Related Questions