I am trying to set/paste an image at the current cursor/caret position. I am using a div
which has contenteditable
set to true
. Here is the HTML portion:
<div class="container">
<div class="row">
<div class="col">
<nav></nav>
</div>
</div>
<div class="row d-flex justify-content-center">
<div id="editor" class="col-md-6" contenteditable="true"></div>
</div>
</div>
This is how the css is set:
#editor {
height: 88vh;
font-size: 0.8em;
}
I am using a javascript function that I found in another StackOverflow post to get the current caret position.
function getCaretPosition() {
var x = 0;
var y = 0;
var sel = window.getSelection();
if (sel.rangeCount) {
var range = sel.getRangeAt(0).cloneRange();
if (range.getClientRects()) {
range.collapse(true);
var rect = range.getClientRects()[0];
if (rect) {
y = rect.top;
x = rect.left;
}
}
}
return {
x: x,
y: y,
};
}
I am using this function inside a key-down event listener to capture when to paste the image. The idea is to paste when the user hits Ctrl + q, for example.
editor.addEventListener(
'keydown',
(event) => {
const keyName = event.key;
if (keyName === 'Control') {
return;
}
if (event.ctrlKey) {
if (keyName == 'q') {
var image = document.createElement('img');
image.src = 'img/bird.jpg';
image.style.width = '200px';
image.style.position = 'absolute';
image.style.top = getCaretPosition().y;
image.style.left = getCaretPosition().x;
editor.appendChild(image);
}
}
},
false
);
The following things happen now:
I want it to be able to paste the image top and left corner at the current caret position. If there are texts, then it is desirable to move/shift them after the image, as if they are making space for the image.
Thanks for any ideas.