I'm having a contenteditable
div. I want to replace smiley code to smiley image on keyup/keydown events. I've understood the marked answer code of question Replace smiley codes to images for replacing smiley codes to images.
And so I tried to modify it for keyup/keydown events but, it is not working. Below is the snippet of modified code with that answered one.
var emoticons = {
':-)' : 'chair.gif',
':)' : 'cheers1.gif',
':D' : 'clapping.gif',
':-|' : 'dance.gif'
};
var url = "http://digitalsetups.com/emoji/";
var patterns = [];
var metachars = /[[\]{}()*+?.\\|^$\-,&#\s]/g;
// build a regex pattern for each defined property
for (var i in emoticons) {
if (emoticons.hasOwnProperty(i)){ // escape metacharacters
patterns.push('('+i.replace(metachars, "\\$&")+')');
}
}
// Building Regex Expression
var regex = new RegExp(patterns.join('|'),'g');
// My modification starts here to replace smiley code to image on keyup/keydown events
$(document).ready(function(){
$("#chatMessage").keyup(function(){
// var start = this.selectionStart;
$("#chatMessage").html($("#chatMessage").html().replace(regex,
function (match) {
return typeof emoticons[match] != 'undefined' ?
'<img src="'+url+emoticons[match]+'"/>' :
match;
}));
// this.selectionEnd = start;
});
});
#chatMessage {
max-height: 20px;
max-width: 400px;
overflow: auto;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
</head>
<body>
<div id="chatMessage" contenteditable>This is contenteditable div. Press space to change :) into image. Or :-) into another image.</div>
</body>
</html>
UPDATE:
- I have updated JQuery code. Changed
val()
tohtml()
inkeyup function()
definition. When I changed it, codes change to image upon keyup but the cursor moves to beginning of line every time I write 1 character. - I've tried the solution of
selectionStart
andselectionEnd
(which I've commented it in the code.) Nothing happens. Also, if I specify start position to be selectionEnd and end position to be selectionStart then, cursor works but smiley codes do not change then.