Skip to content

Instantly share code, notes, and snippets.

@mrinalwadhwa
Created June 15, 2012 05:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrinalwadhwa/2934854 to your computer and use it in GitHub Desktop.
Save mrinalwadhwa/2934854 to your computer and use it in GitHub Desktop.
Justify text if hyphens:auto is supported
var addStyleSheet = document.createStyleSheet || function(styles){
var css = document.createElement('style');
css.setAttribute("type","text/css");
css.appendChild(document.createTextNode(styles));
document.getElementsByTagName('head')[0]).appendChild(css);
}
function isHyphensAutoSupported(result){
try {
var
d = document,
b = d.body,
container = d.createElement('div'),
div1 = d.createElement('div'),
div2 = d.createElement('div'),
span1 = d.createElement('span'),
span2 = d.createElement('span'),
divStyle1 = div1.style,
divStyle2 = div2.style,
text = 'Antidisestablishmentarianism',
cssText
= 'position:absolute;top:0;left:0;width:5em;'
+ 'text-align:justify;text-justification:newspaper;';
divStyle1.cssText = cssText;
divStyle2.cssText
= cssText
+ '-moz-hyphens:auto;-webkit-hyphens:auto;'
+ '-o-hyphens:auto;-ms-hyphens:auto;hyphens:auto;';
span1.innerHTML = text;
span2.innerHTML = text;
div1.appendChild(span1);
div2.appendChild(span2);
container.appendChild(div1);
container.appendChild(div2);
b.insertBefore(container, b.firstElementChild || b.firstChild);
result =
span1.offsetHeight != span2.offsetHeight
|| span1.offsetWidth != span2.offsetWidth;
b.removeChild(container)
} catch(e){}
return result
}
// if hyphens: auto is supported, then justify text
isHyphensAutoSupported() && addStyleSheet('p{text-align:justify}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment