I come across all sorts of weird and wonderful requests as part of the job.
This one turned up when I was trying to split names onto two lines on mobile devices and keep them on one line for desktop widths within a h3 tag. I hesitated to hardcode span elements around the words in the post title field in WordPress as users would be editing and adding these themselves, and we all know users have a penchant for forgetting things, omitting stuff and just getting stuff wrong! Hehehe ;P Love you guys really!

Check it out:

$('section h4').each(function(){
    var string = $(this).html(); 
    n = string.indexOf(" ") + 1;
    if(n !== 0) {
       string = string.substr(0,n) + '<span>' + string.substr(n) + '</span>';

Quick explanation:
For each h4 in the section grab the html (i.e. the name) and find what position the space is with indexOf.
If there is no space don’t do anything, but if there is then add span tags around the second part and replace the html in the h4 tags.
The span then controls when it breaks onto a new line!

Leave a Reply

Privacy & more..

Cookie Consent Policy