How to insert a HTML tag into the same <div> tag in a single keypress event? (in JQuery or Javascript)

Viewed 166

I want to insert a HTML tag in a keypress event. I am new to JQuery and Javascript, and I've also searched for this thing, but got no answer for this thing

I know about the append and selectionStart methods but i want to insert at the position of text cursor

For Eg., if i type the letter 'a', it should send <img src='a.png'> to the div, at the cursor position

$("#textcontent").contentEditable = "true";

$(document).ready(function(){
  $("#textcontent").keydown(function(event){ 
    $("#textcontent").append("<img src='" + event.key +".png'>");

But, This (JS append code at the top) is not i want, but i want to insert a HTML tag at the current text cursor position

My HTML:

<div class="textcontent" contenteditable="true">
  <img src='h.png'>
  ... // more image tags goes here
</div>

Can anybody pls give some answers for this problem?

2 Answers

Check this out:

image 1

image 2


$("#textcontent").keydown(function(event) {
  if (event.key === "Backspace") return; // allow backspace to clear image
  if (!/^[a-zA-Z0-9]{1,1}$/.test(event.key)) return false; // just allow a-z and 0-9

  const position = document.getSelection().anchorOffset; // get position
  const newElement = $(`<img alt="${event.key}" src="https://eu.ui-avatars.com/api/?name=${event.key}">`); // create new element
  const element = [...$("#textcontent img")][position]; // get previous element on index "position"
  if (element)
    textcontent.insertBefore(newElement.get(0), element); // prepend element
  else $("#textcontent").append(newElement); // append element
  
  /* OPTIONAL! place caret at the end */
  textcontent.focus();
  const range = document.createRange();
  range.selectNodeContents(textcontent);
  range.collapse(false);
  const selection = window.getSelection();
  selection.removeAllRanges();
  selection.addRange(range);
  /**/
  
  return false; // cancel event to avoid text inside div
});
#textcontent {
  border: 2px solid gray;
  padding: 10px;
  border-radius: 10px;
}
img {
  margin-left: 7px;
  width: 30px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="textcontent" contenteditable="true"></div>

I've made some changes on @jns's code and this is what i've came up with...

Added the function to use lowercase characters, space and also for some other symbols...

Thank you @jns!

$("#textcontent").keydown(function(event) {
  if ((event.key === "Backspace")||(event.ctrlKey)||(event.altKey)||(event.keyCode == 46)||(event.which>=33 && event.which <=40)) return; // Allow other keys to do their normal functions (not for Enter key)
  if (!/^[a-zA-Z0-9\/`~=\[\]'\\; ]$/.test(event.key)) return false; // Just allows A-Z, a-z, 0-9, and also characters like `~=[];'\/
  var letter_name = event.key;
  var uppercase = "false";
  if (event.key === ' ' || event.key === 'Spacebar') // To add spacebar input feature ('Spacebar' for IE9 and Firefox < 37)
    letter_name = '';
  else
    letter_name = event.key;
  if (/^[A-Z]$/.test(letter_name)) // To chech whether its an uppercase letter
    uppercase = "true";
  else
    uppercase = "false";
  const position = document.getSelection().anchorOffset; // get position
  const newElement = $(`<img alt="${letter_name}" src="https://eu.ui-avatars.com/api/?uppercase=${uppercase}&name=${letter_name}">`); // create new element
  const element = [...$("#textcontent img")][position]; // get previous element on index "position"
  if (element)
    textcontent.insertBefore(newElement.get(0), element); // prepend element
  else $("#textcontent").append(newElement); // append element

  /* OPTIONAL! place caret at the end */
  textcontent.focus();
  const range = document.createRange();
  range.selectNodeContents(textcontent);
  range.collapse(false);
  const selection = window.getSelection();
  selection.removeAllRanges();
  selection.addRange(range);
  /**/

  return false; // cancel event to avoid text inside div
});
#textcontent {
  border: 2px solid gray;
  padding: 10px;
  border-radius: 10px;
}

img {
  margin-left: 7px;
  width: 30px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="textcontent" contenteditable="true"></div>

Related