JSFiddle - React, Tailwind, and code Playground
by aymanj
HTML
<script src="https://jcaret.googlecode.com/files/jquery.caret.1.02.min.js"></script>
<div class='container'>
<div class='highlighted'></div>
<textarea class='text_area'>hi my name is Ayman</textarea>
</div>
CSS
.container{
position: relative;
float: left;
}
.container textarea{
background: transparent;
width:400px;
height: 100px;
resize: none;
line-height: 14px;
font-size:14px;
}
.container .highlighted{
position: absolute;
background: #D4E0F6;
color: #131417;
border: 1px solid #ACC2EE;
width: 43px;
height: 16px;
left: 113px;
top: 2px;
z-index: -1;
}
JavaScript
$(document).ready(function(e){
$('.text_area').bind('keypress', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 64){
$('.text_area').val($('.text_area').val()+" Ayman")
line = $('.text_area').val().substr(0, $('.text_area').selectionStart).split("\n").length;
var hl = $("<div class='highlighted'></div>");
$(hl).css({'left':$('.text_area').getCursorPosition()+"px", 'top': ((line*14)-12)+"px"})
$('.container').append($(hl))
}
});
});
(function ($, undefined) {
$.fn.getCursorPosition = function() {
var el = $(this).get(0);
var pos = 0;
if('selectionStart' in el) {
pos = el.selectionStart;
} else if('selection' in document) {
el.focus();
var Sel = document.selection.createRange();
var SelLength = document.selection.createRange().text.length;
Sel.moveStart('character', -el.value.length);
pos = Sel.text.length - SelLength;
}
return pos;
}
})(jQuery);