When typing text into a textarea and it becomes wider than the area, the text is wrapped onto the next line. Is there a way I can programmatically determine when this happen
You can measure every line width using a "hidden" span.
If the line width is greater than the textarea width then the line is wrapped
demo here
function textWidth(txt, font, padding) {
$span = $('<span></span>');
$span.css({
font:font,
position:'absolute',
top: -1000,
left:-1000,
padding:padding
}).text(txt);
$span.appendTo('body');
return $span.width();
}
There's no actual event fired when the wrapping occurs, but you can hack a solution if you know the width of the textarea.
Listen for the change event on the text area and transfer the text into a div that wraps to it's content;
<div class="textwidth"></div>
With style:
.textwidth {
position: absolute;
visibility: hidden;
height: auto;
width: auto;
}
Calculate the width of the div with the text content and compare that to the constant width of the textarea:
$('textarea').on('keyup', function() {
var lastLine = $(this).val().split('/n').pop();
var width = $('.textwidth').text(lastLine).width();
if ( width > $('textarea').width() ) {
// fire wrap event
}
});
Here's a bit of a shoddy fiddle that should give you some idea how to continue: http://jsfiddle.net/cXbAh/1/