Last active
October 5, 2015 21:41
-
-
Save Firestorm980/a705690f194249aea2b2 to your computer and use it in GitHub Desktop.
jQuery Fix Orphans
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* This script is modified from Ricardo Zea: http://codepen.io/ricardozea/pen/qcDCJ | |
* His was a modified script from CSS-Tricks: https://css-tricks.com/preventing-widows-in-post-titles/ | |
* It should be able to modify the last word of the selector and make it so there is no orphan when there is no room using the trick. | |
* May adapt it into a plugin. | |
*/ | |
jQuery(document).ready(function($) { | |
$('p').each(function() { | |
var wordArrayRaw = $(this).html().split(' '); // Get an array of words | |
var wordArray = wordArrayRaw.filter(function(n){ return (n !== undefined && n !== ''); }); // Filter out the bad | |
// Are there enough words to work with? | |
if (wordArray.length > 1) { | |
// Exclude tags within the query | |
if ( wordArray[0].indexOf('<') < 0 || wordArray[wordArray.length-1].indexOf('>') < 0 ){ | |
wordArray[wordArray.length-2] += ' '; // 2nd to last word, add a non-breaking space | |
// Remove the last word from the array | |
// We to this so that later when we "join", spaces are correct. | |
var lastWord = wordArray.pop(); | |
// Create the final HTML | |
var finalString = wordArray.join(' ') + lastWord; | |
// Replace the HTML with our new HTML | |
$(this).html( finalString ); | |
} | |
} | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment