Friday 30 August 2013

Change font size of iframe content with Javascript dynamically (No jquery)

Share |
You want to allow your site visitors to change the font size of your site. You know there are examples aplenty online so it would be done in a jiffy. But alas, there are iframes on your site, and this stubborn content refuses to change no matter how hard you try.

"Give me something that just works!" screams in your mind.

Allow users to change font size

If you just want to know how you can access iframe content through javascript, see below. Many solutions employ the jquery library, but not for our case.

function changeIframeFontSize(size) {

var x=document.getElementsByName("iframeName"); //point 1
var y=(x.contentWindow || x.contentDocument);            //point 2
 
var styleElements=['table','p']; //point 3
var j; var i;                                                                    // the loop index
               
   for (j=0; styleElements[j]; j++) {
if (y.document)                                                                    //point 4
x=y.document.getElementsByTagName(styleElements[j]);       
for(i=0; x[i]; i++)
x[i].style.fontSize=size;                                                  //point 5
}
}

Point 1: getElementsByName gets you the reference to your iframe with attribute name of "iframeName".
Eg. <iframe src="/default.asp" name="iframeName"> </iframe>

Point 2: does the magic of actually allowing you to access the DOM elements of your iframe contents.

Point 3: we create this array here, because we want only selected elements in our iframe content affected. So we populate it with the relevant tags that we want.

Point 4: the for loop basically loops through the all the html tags found with getElementsByTagName (variable x is reused solely for convenience sake), and finally...

Point 5: sets the font size dynamically for each and every element.

You can use the above example to build on the work done here, setting them in the resize and reset methods: http://www.dyn-web.com/code/fontsizer/documentation.php#examples

I will post my implementation if there are requests.

Note: This only works if the iframe content belongs on the same domain, eg not from another external site.

1 comment:

  1. Yes please post your implementation this is exactly what I've been searching for.

    ReplyDelete

Comments will be moderated.
You can always click 'Contact me' link to get in touch directly.