Putting everything together with jQuery. Let me know if you need a JavaScript block.
$(function() {
var textProps = [0, 0];
$("textarea.allow-overflow").keyup(function(e) {
var self = $(this);
var text_width = $(".hidden").text(self.val()).css({
'font-weight': self.css("font-weight"),
'font-size': self.css("font-size"),
'font-family': self.css("font-family"),
'white-space': 'nowrap',
'position': 'absolute',
'display': 'block',
'width': 'auto'
}).hide().width();
textProps[0] = $(".hidden").width();
textProps[1] = $(".hidden").height();
var overflows = text_width > self.width();
var lines = 1;
if (overflows) {
lines = Math.floor(self.prop("scrollHeight") / $(".hidden").height());
textProps[0] = textProps[0] - (self.width() * (lines - 1));
textProps[1] = $(".hidden").height() * lines;
}
$(".report").html("X (Left): " + textProps[0] + "px, Y (Top): " + textProps[1] + "px, Wrap: " + overflows.toString() + ", Lines: " + lines);
});
});
.widget label {
display: block;
}
.widget .allow-overflow,
.report {
width: 240px;
font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;
font-size: 13px;
font-weight: 400;
}
.report {
border: 1px dashed #ccc;
font-size: 9px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="widget">
<label>Type in me</label>
<textarea class="allow-overflow"></textarea>
</div>
<div class="report"> </div>
<div class="hidden"></div>
We need to know a few things.
- When we have overflowed and are wrapping in the text box.
- The width and font properties of the text box
- The line height of the text
We can then calculate the current cursor position from the [X (Left), Y (Top)]
of the text box. When we enter text, it then increases the width
and height
of the hidden div.
On the first line, this is easy, x
= width
and y
= height
. Once we have wrapped, we now have to calculate an offset and the number of lines.
number of lines = floor( text box scroll height / hidden height )
x pos on line = hidden width - (width of text box * number of lines)
y pos = line height * number of lines
You can push this into a function and cleanup the resulting data into an array or object.
If you allow for resizing, then we cannot count on static width and height of text box. So, for my example, I grab that detail each time.
Hope that helps.