Skip to content

Instantly share code, notes, and snippets.

@agibsonsw
Created April 30, 2012 20:16
Show Gist options
  • Save agibsonsw/2562348 to your computer and use it in GitHub Desktop.
Save agibsonsw/2562348 to your computer and use it in GitHub Desktop.
JS to tidy/align spaces
function tidySpaces() {
var olCode, spans, i, span_textnode, span_text, span_next, offLeft, newLeft;
if (document.getElementsByClassName) {
spans = document.getElementsByClassName('tidy');
if (spans != 'undefined' && spans.length) {
for ( i = 0; i < spans.length; i++ )
spans[i].style.paddingLeft = (spans[i].style.paddingLeft == '0px') ?
spans[i].prevValue : '0px';
return;
}
}
olCode = document.getElementById('olCode');
spans = olCode.getElementsByTagName('span');
for (i = 0; i < spans.length; i++) {
if ( spans[i].previousSibling ) {
if ( spans[i].className && spans[i].className == 'comment')
continue;
span_textnode = spans[i].firstChild;
span_text = span_textnode.data;
tidied = span_text.replace(/\s{2,}$/,'');
if (span_text.length && (span_text.length > tidied.length)) {
if ( spans[i].nextSibling ) {
span_next = spans[i];
while ( (span_next = span_next.nextSibling) && span_next.className
&& span_next.className == 'comment' && span_next.nextSibling )
; // do nothing, get next span (or 'a' tag)
if ( span_next ) {
offLeft = span_next.offsetLeft;
newLeft = (parseInt(offLeft / 60)) * 60 + 60;
span_next.style.paddingLeft = (newLeft - offLeft) + 'px';
span_next.className = 'tidy';
span_next.prevValue = span_next.style.paddingLeft;
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment