I am trying to implement something like the input box of chat window of facebook where with the click of space bar text can be converted into emoji. With my code, whenever the conversion happens, the caret goes back to the beginning of div. And also, I want the function convert() to be called as long as there is text present in div.But after one conversion the code stops working and I have to click outside and then inside the text box for the conversion to take place.How can I implement these things correctly?
var data={
"value":":)",
"image":"https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcSaW1KOeceO85Y7KfUXGyLZm1LfTwjhQspKKXUl3D3a5Mo1uz-AhA"
};
$(document).ready(function(){
convert();
function getWord(text){
var word=text.split(" ").pop();
return word;
}
function setCursor(i){
i++;
console.log(i);
var el = document.getElementById("image");
var range = document.createRange();
var sel = window.getSelection();
range.setStartAfter(el);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
function convert(){
document.body.onkeyup=function(e){
var contenteditable = document.querySelector('[contenteditable]');
text = contenteditable.textContent;
if(e.keyCode==32){
var word=getWord(text);
if(word.includes(data.value)){
var i=0;
var img = "<img id='image'"+i+" src='" + data.image +"' class='image' /> ";
console.log(img);
$("#text-box").html(function (_, html) {
return html.replace(data.value , img );
});
setCursor(i);
//$("#text-box").html(text.(replace(data.value,img));
//document.getElementById('textbox').replaceChild(data.value,img);
}
}
}
}
});
<html>
<head>
<style type="text/css">
.image{
position: relative;
max-height: 1.4em;
max-width: 1.4em;
}
[contenteditable]{
-webkit-appearance:textfield;
appearance:textfield;
border: 1px solid black;
line-height:1.4em;
min-height: 20px;
}
</style>
</head>
<body>
<div contenteditable="true" id='text-box'>
</div>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script type="text/javascript" src="emoji.js"></script>
<script type="text/javascript" src="data.json"></script>
</body>
</html>