I'm trying to wrap a class around the first or the second half of a headline so that I could create more dynamic and cool headlines with jQuery.
In theory I want to find all of the spaces in the sentence and divide it into two. If the headline contains an uneven number of words the script should detect that and also add the class to the nearest word.
This is an interesting problem. I would approach with the handy javascript splice method. Splice can be used to insert and delete items of an array. I'd recommend opening up an inspector and trying out some of the examples I've written below.
First we'll use jQuery to select the header then manipulate the html content string. I'm assuming that the specific header you want to manipulate will have a class and I've substituted 'dynamic':
var header = $("h1.dynamic").text();
=> "Header with some other stuff"
var header_as_array = header.split(" ")
=> ["Header", "with", "some", "other", "stuff"]
var first_half = header_as_array.splice(0, header_as_array.length/2)
Keep in mind that splice changes the original array, so at this point:
first_half = ["Header", "with"]
header_as_array = ["some", "other", "stuff"]
Now, you can join them back together and wrap them with spans like so:
var first = '<span class="first_half">'+first_half.join(" ")+'</span>';
var second = '<span class="second_half">'+header_as_array.join(" ")+'</span>';
var finished = first+" "+second;
Finally, we'll put our finished string back into the header with jQuery:
$("h1.dynamic").html(finished);
The way I've written it a header with an odd number of words will always have the second half as the longer half. If you would prefer it the other way around you could do this:
var splice_location = Math.ceil(test_as_array.length/2);
var first_half = header_as_array.splice(0, splice_location);
By default a non-integer value will be truncated, but here we are using the ceiling function to round things up instead of down.
Nice one @lashleigh. You can have a look at a working example here:
http://jsfiddle.net/johnhunter/KRJdm/
@Tony, I've implemented what you are after as a jquery plugin. You call it on the header you want formatted:
$(function() {
$('h1').splitWords();
});
...and it will produce html output like this:
Before:
<h1>This is a long headline</h1>
After:
<h1>
<span class="wrap-1">This is </span>
<span class="wrap-2">a long headline </span>
</h1>
UPDATED:
Not part of the original question but I have updated the example to allow you to specify at which word the wrapping occurs. If you provide an index argument it will use that offset on the list of words (minus values count back from the end). e.g:
$('h1.a').splitWords(); // Split these words equally
$('h1.b').splitWords(1); // Split these after the first word
$('h1.c').splitWords(-2); // Split these after the second last word
http://jsfiddle.net/johnhunter/KRJdm/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With