Wrapping lines of text using jQuery
View DemoNot long ago, I entered Chris Coyier’s CSS-Off competition. The mock-up was deceivingly harder than it looked, but I managed to put something together that I think should stand a chance of being considered for a prize. The one area that gave me trouble was the use of different colours on different lines of text within an element. I knocked together a quick jQuery plugin to achieve this, and then realised after submitting my entry that it didn’t work at all in Internet Explorer. Doh! Anyways, I have now fixed that, and here is the plugin.
I am not going to go through the code in this post as it is pretty trivial. Essentially, all you need to do is go through each word in block of plain text, wrap it in an inline element, (e.g. a span) then work out each of those element’s top offset from their containing element. By doing this, you can work out which line each word is on. Lastly, you can wrap each line in an element, which can then be styled. Simples!
However, I feel it is worth mentioning a weird IE7/8 bug that I encountered along the way. Basically, when I wrapped each word in span, the first word of each line had an incorrect top offset. In fact, the offset was equal to that of an element on the previous line. There didn’t seem to be any logical reason for this to be happening, other than a browser bug. A quick workaround later and the plugin works in all major browsers.