On button click, I need to insert an element at a specific position within a contenteditable div.
Currently, the content is added at the end of the document instead of where the cursor was placed before clicking the button.
function append_content() {
$("#myBtn").click(function(e) {
var getOffset = $("#div_edit").offset();
var relX = getOffset.left.toString() + "px";
var relY = getOffset.top.toString() + "px";
var ii = $('<span class="span-add">Add a link</span>')
.css({
top: relX,
left: relY
});
$("#div_edit").append(ii);
});
}
<button class="myBtn" id="myBtn">append content</button>
<div contenteditable="true" class="div_edit" id="div_edit">Lorem ipsum dolor sit amet</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
Is there a way to add the content where the cursor was positioned within the specified div ($("#div_edit")
) when clicking outside of it?