Mark up text for responsive – server side javascript

Been working on some server side javascript of late and came up with this function below to get an initial string and mark it up differently so that when CSS is applied that it will truncate the string at smaller screen sizes. It’s to be used with content management system where users wouldn’t know how to add code to show/hide content.

So what we want to happen is that a user can add a string whatever size, and we have set a length that that string should be cut down to when it gets to mobile size screen. It’ll be done by adding spans to the remaining content after the string is cut. Those spans have classes on them which our media queries will look for to show and hide. I’ve added a breaker text too so that it’s obvious that the text has been truncated on purpose.

Use case would be for example news items on a homepage – the CMS users add a title that is very long.. by the time we get down to smaller screen sizes this text takes up half the screen. We want the text to be truncated on smaller screens. I’m using document.write because its server side scripting so it’ll just output what goes in there during the publish from the CMS.

function reMarkText(myString,lengthOfString,breaker){
	if(myString.length < lengthOfString){
		return myString;
	}
	else{
		var shortenedString = myString.substr(0,lengthOfString);
		var remainingCharacters = title.substr(lengthOfString);
	 	return  shortenedString + '<span class="small-only">' + elipsis + '</span>' + ' <span class="large-only">' + remainingCharacters + '</span>'
	}
} //end function reMarkText

var lengthOfSmallVersion = 47;
var elipsis = '...';
var title = "Former US senator to deliver graduation keynote - testosterone trophy driving gloves via plug-and-play networks";

document.write(reMarkText(title,lengthOfSmallVersion, elipsis));

Then the CSS would be something along the lines of

	.large-only{display:inline;}
	.small-only{display:none;}

	@media (max-width: 700px) {
	.large-only{display:none;}
	.small-only{display:inline;}
	 }

If using a framework I’d be looking to hook it up to the visibility classes associated with that framework such as hide-for-small etc.