JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://raw.github.com/bartaz/sandbox.js/master/jquery.highlight.js"></script>
<textarea class="ta parent" id="ta2"></textarea>
CSS
.parent
{
position: absolute;
filter: alpha(opacity=30);
opacity: 0.3;
}
.clone
{
position: relative;
}
.ta
{
width: 300px;
height: 300px;
}
.suggestion {
border-bottom: 1px dashed red;
}
JavaScript
//globals for range of words when clicked
var begin, end;
$(document).ready(function(){
//save reference to ta2, inject ta1
var ta2 = $("#ta2"), ta1 = null;
ta2.val("TESTP\n\n123\n\nTESTING\n\n123\n\nTESTP")
.before("<div style='position:absolute'><textarea class='ta clone' id='ta1'>" + ta2.val() + "</textarea>")
.after("</div>");
//save refrence to ta1
ta1 = $("#ta1");
//apply styling, handlers etc to ta1
ta1.highlight("TESTP", {className:"suggestion"})
.click(function(){
alert("ta1 clicked, I shouldn't happen");
});
//apply handlers to ta2
ta2.click(function(){
GetRange($(this).attr("id"));
if(begin != null && end != null)
alert($(this).val().substring(begin, end));
/*************************************************************
//now how to trigger a click on the corresponding span tag in ta1?...
*************************************************************/
ta1.first("span").click();
});
$(".suggestion").click(function(){
alert("Success! " + $(this).text());
});
});
//helper function just to get range of text that is clicked
function GetRange(id)
{
var element = $("#" + id), caret = element.caret(), data = element.val(), bfound = false, efound = false;
for(var i = caret.begin; i >= 0; i--)
{
if(data.charAt(i) == '\n')
{
begin = i + 1;
bfound = true;
break;
}
}
for(var i = caret.begin; i <= data.length; i++)
{
if(data.charAt(i) == '\n')
{
end = i;
efound = true;
break;
}
}
if(!bfound)
begin = 0;
if(!efound)
end = data.length;
}
//couldn't get jsfiddle to load jquery.highlight plugin from https://raw.github.com/bartaz/sandbox.js/master/jquery.highlight.js so I just included it here as a work around
jQuery.extend({
highlight: function (node, re, nodeName, className) {
if (node.nodeType === 3) {
var match = node.data.match(re);
if (match) {
var...