I have a project in which a content editable div is parent then using jQuery I wish to add p tags inside this div. Which can then also be edited. Almost like a mini note pad document.
The problem I have is that i’m using the jQuery .append function on the parent div which adds the p class to the end of the div. What I need it to do is add the p class after the current selected p / the p the caret cursor is currently inside.
jQuery I am currently using –
$(".addHeading").click(function() {
$('.textArea').append('<div class="heading">Heading</div>');
});
$(".addParagraph").click(function() {
$('.textArea').append('<div class="paragraph">Test</div>');
});
I have put my current code into a JSFiddle. I hope it’s obvious what i’m trying to do.
Any help would be greatly appreciated!
JS Fiddle –
http://jsfiddle.net/eheHS/
Regards
By adding a click handler to your newly created paragraph divs, you can save away the last one that was edited. Here’s one solution, but not very elegant (jsFiddle):
This will set
$lastCaretDivto the last one that was clicked. If it is defined, then add the new paragraph after it, otherwise append it to the text area.My solution has a lot of pitfalls as it is right now, but you have something to work after. I would suggest clearing
$lastCaretDivwhenever something else in the text area is clicked, e.g. a header. It all depends on how you want it to behave.