Colored text
Trying to color a text as the French flag dynamically.
HTML
<p class="loremipsum">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
CSS
.loremipsum {
border-radius: 5px;
font-size: 12px;
width: 500px;
}
.color-0 {
color : blue;
}
.color-1 {
color : white;
}
.color-2 {
color : red;
}
JavaScript
jQuery(function ($) {
// Calculates the text width in <p>
var html_cur = $('.loremipsum').html();
var html_calc = '<span>' + html_cur + '</span>';
$('.loremipsum').html(html_calc);
var width = $('.loremipsum').find('span:first').width();
var color_width = Math.floor(width / 3), // Width of each color
text = $( ".loremipsum" ).text(), // Text of <p>
array = [], // Array containing each sentences
sentence = '', // Current sentence
sentence_width = 0; // Current sentence width
for(var i = 0; i < text.length; i++) {
// Gets the char in the text
var char = text[i];
// Calulates actual char's width in pixels
var html_calc = '<span>' + char + '</span>';
$('.loremipsum').html(html_calc);
var width = $('.loremipsum').find('span:first').width();
// Apply to variables
sentence_width += width;
sentence += char;
// If sentence is long enough,
// resets the variables to start a new sentence and add it to the array
// Added the -10 to make sure sentences never overflow the color_width
// but looks like it's not enough
if(sentence_width >= color_width - 10) {
array.push(sentence);
sentence = '';
sentence_width = 0;
}
}
// Variables for final html
var final_html = '',
color = 0;
// Loops through the sentences and add them in between the correct color
final_html = '<span class="color-0">';
for (var i = 0, j = array.length; i < j; i++) {
final_html += array[i];
color = (color == 2) ? 0 : color + 1;
final_html += '</span><span class="color-'+color+'">';
}
final_html += '</span>';
// Display text on screen
$('.loremipsum').html(final_html);
});