Trying to build a little script for orphaned words:

I wanted to make a really simple script to solve some orphan words in some of my titles. I thought I did a pretty neat job, but then the first words are cut off. Any help understand why?

var buddyUpOrphans = function(element, howMany) {
    $(element).each( function() {
        var $this = $(this);
        var thisText = $this.text().split(' ');
        var wordLength = thisText.length;
        thisText.splice( (wordLength - howMany), 0, '<nobr>');
        thisText.shift('</nobr>');
        thisText = thisText.join(' ');
        $this.html(thisText);
    });
};

      

CodePen

$(document).ready( function() {
    buddyUpOrphans('p', 2);
    buddyUpOrphans('.test1', 4);
});

      

+3


source to share


2 answers


The method .shift

removes the first element of the array (and takes no arguments), whereas it seems that you want to add something to the end of the array. You can use a method .push

for this.

As you add items <nobr>

and </nobr>

an array, and then perform .join(" ")

, it has the unintended consequence of placing spaces around them.

I would recommend concatenating <nobr>

and </nobr>

at the end of some array elements rather than inserting them into the array.



var buddyUpOrphans = function(element, howMany) {
	$(element).each( function() {
		var $this = $(this);
		var thisText = $this.text().split(' ');
		var wordLength = thisText.length;
		thisText[wordLength - howMany - 1] += "<nobr>";
		thisText[wordLength - 1] += '</nobr>';
		thisText = thisText.join(' ');
		$this.html(thisText);
	});
};


$(document).ready( function() {
	buddyUpOrphans('p', 2);
	buddyUpOrphans('.test1', 4);
});
      

body { 
	color: red;
}
	
nobr {
	color: blue;
}
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class='test1'>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eveniet voluptates aperiam cumque, qui error, aliquam velit hic ad sapiente accusamus totam id similique repudiandae doloribus, optio consequatur, voluptatum maiores quod?</p>

<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsa laudantium rem ut id delectus at eaque inventore rerum, dolorem nisi alias modi asperiores recusandae nulla, iure. Facilis consequatur, impedit ipsa.</p>
      

Run codeHide result


+2


source


Because you are using arr.shift()

;



It removes the first element of the array and returns that array. To add items use arr.push()

;

+1


source







All Articles