xy.css

Blog

Abbreviate text for small screens

When designing on or off the grid, it can be challenging to resize or reposition longish strings of text for proper display on small screens. A prime example of this involves scaling list menu-items, which inherently offer limited flexibility.

One solution that has served me well for several years now is to abbreviate the text conditionally with jQuery. For example, given menu items such as these:

We can use jQuery to conditionally modify the items to display like this for small screens:

..which fit much better than trying to style and position the original long strings of text. You can see an example of this sort of menu truncation here at xy.css. Shrink the browser to make it happen.

Abbreviate text with jQuery

Here is the basic jQuery needed to swap long strings of text with appropriate abbreviations. Just include the following snippet along with your other jQuery/JavaScript.

// conditional text abbreviation
function xycss_text_abbrev(){
	if($(window).width() <= 767) {
		$('.docs a').text('Docs');
	} else {
		$('.docs a').text('Documentation');
	}
}
$(document).ready(function(){
	xycss_text_abbrev();
});
$(window).resize(function() {
	xycss_text_abbrev();
});

Then in your markup, ensure that the docs class is included for one of your menu items. Once you see how it works, customize according to your own menu items. To wrap the article, here is the HTML and jQuery required for the previous example menu items.

HTML

<ul>
	<li class="docs"><a href="http://example.com/docs/">Documentation</a></li>
	<li class="faqs"><a href="http://example.com/faqs/">Frequently Asked Questions</a></li>
	<li class="wp"><a href="http://example.com/wp/">WordPress Techniques</a></li>
</ul>

jQuery

// conditional text abbreviation
function xycss_text_abbrev(){
	if($(window).width() <= 767) {
		$('.docs a').text('Docs');
		$('.faqs a').text('FAQs');
		$('.wp a').text('WP');
	} else {
		$('.docs a').text('Documentation');
		$('.faqs a').text('Frequently Asked Questions');
		$('.wp a').text('WordPress Techniques');
	}
}
$(document).ready(function(){
	xycss_text_abbrev();
});
$(window).resize(function() {
	xycss_text_abbrev();
});

Note that with this code, the text-abbreviation happens when the browser window is less than or equal to 767 pixels. For reference, 768 pixels is the width of the iPad (portrait view).

Comments

Comments are closed.