Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

291
Visualizações
How to dynamically set an image in HTML inside a contenteditable div?

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:

  1. If the text field is empty, the image pastes at the current caret position only in the 1st row. If I hit Enter and go to the next few lines, the image gets pasted a line below the current line.
  2. If I type something in the first row, the put the caret to another position, for example beginning of the first row, the image gets pasted at the end of the line, not at the caret position.

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.

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda