Skip to content

Instantly share code, notes, and snippets.

@threedaymonk
Created July 5, 2012 16:11
Show Gist options
  • Save threedaymonk/3054584 to your computer and use it in GitHub Desktop.
Save threedaymonk/3054584 to your computer and use it in GitHub Desktop.
View and test vertical rhythm
(function(){
var isGridActive = false;
var lineHeight = function(){
return parseInt(window.getComputedStyle(document.body).lineHeight, 10);
};
var gridDataURL = function(){
var size = lineHeight();
var canvas = document.createElement("canvas");
canvas.width = 1;
canvas.height = size * 2;
var ctx = canvas.getContext("2d");
ctx.fillStyle = "rgba(128, 0, 255, 0.1)";
ctx.fillRect(0, 0, 1, size);
return canvas.toDataURL("image/png");
};
var addCSS = function(css){
var head = document.getElementsByTagName('head')[0];
var styleElement = document.createElement('style');
styleElement.setAttribute('type', 'text/css');
if (styleElement.styleSheet) { // IE
styleElement.styleSheet.cssText = css;
} else {
styleElement.appendChild(document.createTextNode(css));
}
head.appendChild(styleElement);
};
var addHandler = function(object, eventName, handler){
var oldHandler = object[eventName];
if (typeof oldHandler === 'function') {
object[eventName] = function() {
var args = [].slice.call(arguments, 0);
oldHandler.apply(window, args);
handler.apply(window, args);
}
} else {
object[eventName] = handler;
}
};
var blockElements = [
'ul', 'ol', 'li', 'dl', 'form', 'blockquote',
'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
'pre', 'table', 'p', 'caption'
];
var runTests = function(){
console.log('Running tests:');
var results = [];
var errors = [];
blockElements.forEach(function(tag){
[].forEach.call(document.getElementsByTagName(tag), function(el){
var offset = el.getBoundingClientRect().top % lineHeight();
if (0 == offset) {
results.push('.');
el.classList.add('test-ok');
} else {
results.push('F');
errors.push('Element is off by ' + offset + ' pixels: \n' + el.outerHTML);
el.classList.add('test-fail');
}
});
});
console.log(results.join(''));
errors.forEach(function(e){ console.log(e) });
};
var setup = function(){
addCSS("body.cellsActive * { background-color: rgba(0,255,0,0.15); }");
addCSS("body.gridActive { background-image: url(" + gridDataURL() + ") !important; }");
addCSS(".test-fail { outline: 1px solid red; }");
};
addHandler(window, 'onload', setup);
addHandler(window, 'onload', runTests);
addHandler(window, 'onkeyup', function(evt){
switch (evt.keyCode) {
case 71: // g for grid
document.body.classList.toggle("gridActive");
break;
case 67: // c for cells
document.body.classList.toggle("cellsActive");
break;
}
});
})()
@Hainesy
Copy link

Hainesy commented Jun 11, 2013

This is genius, thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment