I was interested in writing a small script that can offer buttons for increasing and decreasing text size. This is just a learning exercise (I’m a noob). I Googled scripts for this, but all of them were obtrusive. I’d like to make this unobtrusive, but also as efficient as possible. I’ve modified this script to make it unobtrusive, and it works, but I suspect this could be done a lot better.
<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>TextResize</title>
<style media="all">
body {font: 100% serif;}
.buttons span {display: inline-block; padding: 20px; background: #f7f7f7; cursor:pointer}
.buttons span:hover {background: orange;}
.buttons span:focus {background: green; outline: none;}
</style>
</head>
<body>
<p>This is text this is text this is text this is text this is text this is text this is text this is text this is text this is text this is text this is text this is text this is text this is text this is text this is text this is text this is text this is text this is text this is text this is text this is text</p>
<script>
var d = document;
var div = d.createElement("div");
div.setAttribute("class","buttons");
var spanBig = d.createElement("span");
spanBig.setAttribute("tabindex","0");
var bigText = d.createTextNode("Bigger");
spanBig.appendChild(bigText);
var spanSmall = d.createElement("span");
spanSmall.setAttribute("tabindex","0");
var smallText = d.createTextNode("Smaller");
spanSmall.appendChild(smallText);
div.appendChild(spanBig);
div.appendChild(spanSmall);
d.body.appendChild(div);
spanBig.onclick = function() {
resizeText(10);
}
spanSmall.onclick = function() {
resizeText(-10);
}
function resizeText(multiplier) {
if (d.body.style.fontSize == "") {
d.body.style.fontSize = "100%";
}
d.body.style.fontSize = parseFloat(d.body.style.fontSize) + multiplier + "%";
}
spanBig.onkeypress = spanBig.onclick;
spanSmall.onkeypress = spanSmall.onclick;
</script>
</body></html>
Does anyone have any suggestions on how to tighten this up a bit? I really dislike having the two .onclick references. (I added a few extra bits to make it keyboard accessible, too, which is another requirement. I’d also love it if the natural browser resizing would still work, too—i.e. Command + 0 to reset the page. Hate the way JS disables normal browser bahavior—but then, I like to keep my cake and eat it too.)