Previous Message
Next Message

[css-d] CSS DOM Element Switching

Sent by Plagiarist.com on 18 April 2002 18:06


Greetings,

I was thinking of using the style switcher found at ALA, but really only 
wanted to be able to change the font size - with a button, just like the 
alistapart.com site does (they have all the coolest toys over there).

I still don't know if my method is superiour or not to switching style 
sheets on the fly, but here 'tis.  I'm posting this to a) maybe contribute 
something positive to the list, and b) to get hacked to shreds by posts 
saying "You can't do that, dummy!"

So please be gentle, and let me know if I've gone terribly awry (I'm 
posting the bits with code between <pre> tags since I think some e-mail 
clients will actually parse the HTML/Javascript - even if the content-type 
of the message is text/plain).

--------------------------------------------------------------------

Basically, I'm just using a little bit of javascript:

<pre>

<script type="text/javascript">
function changeBig(id)
{
         if (document.getElementById)
         {
         var nodeObj = document.getElementById(id)
         nodeObj.style.fontSize = '16px';
         }
}
function changeSmall(id)
{
         if (document.getElementById)
         {
         var nodeObj = document.getElementById(id)
         nodeObj.style.fontSize = '12px';
         }
}
</script>

To change the font-size (you can't have hyphens in the DOM for elements - 
so all hyphenated elements are written without the hyphen and with a 
capital letter for the second word) you need to use the DOM method 
"getElementById" to get the id selector of the div that you want to change 
(more below).  I'm using a variable (id) so that I can use this in several 
places on my site (using different id selectors).

The nodeObj is the object in the document tree.

If you wanted to just increase the size (or colour, lineHeight, whatever) 
of the text in <p>paragraphs</p> you could use:

document.getElementsByTagName ('p')

instead.

I had originally used the <button> tag for my buttons, but for some unknown 
reason (does anybody know?) "onClick" is not supported in my XHTML version.

So I used a form, which *does* allow "onClick" events:

<form action="nada">
<input type="button" onClick="changeBig('ChangeMe'); return false;" 
value="Larger Text" /><br />
<input type="button" onClick="changeSmall('ChangeMe'); return false;" 
value="Default Size" />
</form>

<div id="ChangeMe">
This text will get bigger or smaller as you press the buttons.
</div>

</pre>

And there you have it.

You can see an example here:

http://www.plagiarist.com/poetry/?action=random

and of course, it validates. :)

-- Jough


+---------------------------+-----------------------+
|Plagiarist Poetry Archive  |  Mature poets steal.  |
|http://www.plagiarist.com  |       -- T.S. Eliot   |
|                           | [EMAIL-REMOVED] |
+---------------------------+-----------------------+
Previous Message
Next Message