Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I made a little <a href="http://jsfiddle.net/Qz4qc/" rel="nofollow noreferrer">script here</a>, with the help of <a href="https://stackoverflow.com/questions/4392868/javascript-find-divs-line-height-not-css-property-but-actual-line-height/4515470#4515470">this function</a> to find line height.</p> <p>It's just an approach, it may or may not work, didn't have time to test throughly.</p> <p>As of now, <code>text_element</code> must be a jQuery object.</p> <pre><code>function avoidBastardWord( text_element ) { var string = text_element.text(); var parent = text_element.parent(); var parent_width = parent.width(); var parent_height = parent.height(); // determine how many lines the text is split into var lines = parent_height / getLineHeight(text_element.parent()[0]); // if the text element width is less than the parent width, // there may be a widow if ( text_element.width() &lt; parent_width ) { // find the last word of the entire text var last_word = text_element.text().split(' ').pop(); // remove it from our text, creating a temporary string var temp_string = string.substring( 0, string.length - last_word.length - 1); // set the new one-word-less text string into our element text_element.text( temp_string ); // check lines again with this new text with one word less var new_lines = parent.height() / getLineHeight(text_element.parent()[0]); // if now there are less lines, it means that word was a widow if ( new_lines != lines ) { // separate each word temp_string = string.split(' '); // put a space before the second word from the last // (the one before the widow word) temp_string[ temp_string.length - 2 ] = '&lt;br&gt;' + temp_string[ temp_string.length - 2 ] ; // recreate the string again temp_string = temp_string.join(' '); // our element html becomes the string text_element.html( temp_string ); } else { // put back the original text into the element text_element.text( string ); } } } </code></pre> <p>Different browsers have different font settings. Try to play a little to see the differences. I tested it on IE8 and Opera, modifying the string every time and it seemed to work ok.</p> <p>I would like to hear some feedback and improve because I think it may come in handy anyway.</p> <p>Just play with it! :)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload