JSFiddle - React, Tailwind, and code Playground
by gion_13
HTML
<hr />
<p>The first paragraph</p>
<p>The second paragraph</p>
<hr />
CSS
p{
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-o-user-select: none;
user-select: none;
}
.custom-span{
background-color : red;
border-radius:5px;
height : 10px;
width : 10px;
display : inline-block;
}
JavaScript
var span = $('<span/>').css({position:'absolute',left:-99999,visibility:'hidden'}).appendTo('body');
$('p').click(function(e){
var offset = {
e.pageX - $(this).offset().left,
e.pageY - $(this).offset().top
},
h = $(this).height(),
w = $(this).width(),
txt = $(this).text(),
i = 0;
var ruler = span.text('');
var j = $(this).html().indexOf('<span');
var _w = j>=0 ? $(this).find('.custom-span').width() : 0;
while(++i < txt.length)
if(ruler.width() >= offset.left + (j < i ? _w : 0))
break;
else
ruler.text(txt.substr(0,i));
if(i < 2)
var k = i;
else
k = ruler.text(txt.substr(0,i-1)) - offsetLeft + (j < i-1 ? w : 0) > ruler.text(txt.substr(0,i-2)) - offsetLeft + (j < i-2 ? w : 0) ? i-1 : i-2;
$(this).html(txt.substr(0,k) + '<span class="custom-span"></span>' + txt.substr(k));
});