2
votes

I found some code at http://labnol.blogspot.com/2006/12/allow-site-visitors-to-change-font.html to allow folks to change font size and adapted it to use buttons.

<html>
<head>

<script language="JavaScript" type="text/javascript">
function changeFontSize(inc)
{
  var p = document.getElementsByTagName('*');
  for(n=0; n<p.length; n++) {
    if(p[n].style.fontSize) {
       var size = parseInt(p[n].style.fontSize.replace("px", ""));
    } else {
       var size = 16;
    }
    p[n].style.fontSize = size+inc + 'px';
   }
}
</script>

</head>
<body>
<basefont size=3/>
<p>
asdf
hhui
jnj
ghvt
</p>

<input type="button" value="+" onclick="changeFontSize(1)" />
<input type="button" value="-" onclick="changeFontSize(-1)" />

</body>
</html>

I am aware of browser features such as ctrl mouse wheel to change font size.

I have some problems with this...

1) How can I discover what the constant 16 should be rather than code it in? 2) Is there anyway to cause the font change to effect pages linked to by this page?

On another vein. If one uses something like the mouse wheel to change font size, my browser (Firefox) remembers the font size whenever the page is visited even in new executions of the browser. Are there other places accessible to java to set/discover this information?

2
Just to clarify, you're talking about Javascript and not Java, right?theycallmemorty
yup, thought that was what I selected as a tag, sorry :-(Mike D
I changed the title so it says JavaScript instead of Javaepascarello

2 Answers

0
votes

Here's a JavaScript function you can use to calculate the size of 1em in pixels:

function getEmSize(el) {
    // If you pass in an element ID then get a reference to the element
    if (typeof el == "undefined") el = document.documentElement;

    var tempDiv = document.createElement("DIV"); 
    tempDiv.style.height = 1 + "em";
    // Just in case the content of "el" takes up it's container's height :)
    tempDiv.style.marginTop = -1 + "em";

    el.appendChild(tempDiv);
    var emSize = tempDiv.offsetHeight;
    el.removeChild(tempDiv);
    return emSize;
}

I also wrote an article about Changing Text Size On Click. Just make sure you save the preference via a cookie or localStorage.

Hope that's useful.

0
votes

The easiest thing to do is to change your page to not use pixels. If you used ems, all you would do is have to change the font size of the body element and everything else would adjust.

Most browsers have the ability to change the font size built in so coding this is really of no benefit if you code the page correctly to begin with.