If I understood you correctly, you want to get the text of the line you clicked on. If that is so, then the following works with your example:
$("#mytextArea").on("mouseup", function(eventData) {
var lineHeight = $(this).css("line-height");
lineHeight = parseInt(lineHeight.substring(0, lineHeight.length - 2));
var line = Math.floor(eventData.offsetY / lineHeight);
alert($(this).val().split("\n")[line]);
});
DEMO - Get Text from clicked line in textarea
The code will take the position the mouse was clicked in within the textarea offsetY
and divide it by the applied line-height
. Using Math.floor()
it will get the line which was clicked and use it as the index element in the array when splitting the lines by "\n"
.
In addition to make this work I enforced the line-height to be a set px
value to allow me to calculate the line clicked.
textarea{
font-size: 15px;
line-height: 15px;
}
Edit - Scrollbars on textarea
Assuming the textarea has a scrollbar, the scrollbar will "distort" the offsetY
value and you need to add the current scroll position to it like this:
$("#mytextArea").on("mouseup", function(eventData) {
var scrollPosition = $(this).scrollTop()
var lineHeight = $(this).css("line-height");
lineHeight = parseInt(lineHeight.substring(0, lineHeight.length - 2));
var line = Math.floor((eventData.offsetY + scrollPosition) / lineHeight);
alert($(this).val().split("\n")[line]);
});
DEMO - Get Text from clicked line in textarea with scrollbar
I updated the CSS to a fixed height to get a scrollbar like this:
textarea{
font-size: 15px;
line-height: 15px;
height: 100px;
}