Micro RFP: JavaScript Dynamic Style Changer


I don’t have the skill to do something that might be really simple for you to do. If you think you can help, please leave a note or email me with your thoughts. Thanks!

Need: I want a small JavaScript function that will parse through each of a certain type of CSS element on a page, one at a time, and assign a specific (random or otherwise dynamically-generated) CSS stylesheet change to each of them.

Reason: There’s a basic incompatiblity between CSS as a system of strictly styling page elements and my own personal sketchbook/design style of making unique, idiosyncratic, and often random changes to each element on a page. Right now, I specifically want to try randomly assigning a new color to every hyperlink on a page.


5 responses to “Micro RFP: JavaScript Dynamic Style Changer”

  1. When you say “a certain type of CSS element”, do you mean an HTML element, or a CSS id/class? Either way that would be pretty easy – you’d just have to specify the type of change needed.

    For your new colour for hyperlinks, you need to grab every A tag into an array:

    var all_links = document.getElementsByTagName(‘a’);

    Then iterate through each one in turn, changing the colour style property of the link:

    for (var i=0,len=all_links.length;i

  2. Hmm – is there a maximum length permitted for these comments?

    The last bit should be:

    var colors = array(‘000′,’333′,’666′,’999’);
    for (var i=0,len=all_links.length;i++) {
    var randcol = Math.floor(Math.random()*colors.length);
    all_links[i].style.color = ‘#’ + colors[randcol];

  3. Thanks Matthew! As you can see, I’ve tried it out. Works like a charm (after a little tweaking)! I’ll leave it active for a while and see if I like it. I already know I don’t like it in the footer and in the post titles.

    I fear that getElementsByTagName works on the raw HTML, and doesn’t allow the kind of CSS class-specific control I want. For example, I’d like to limit the color changes to just the A tags within certain DIVs — specifically, the posts themselves: I don’t need the color changes in the titles, the footer, etc. These areas are neatly delineated in div class=”entry”, and I could in theory also name these divs.

    I’d also like to make the color change just to the un-followed links — the visited and hover styles shouldn’t change. Any thoughts?

  4. I changed my mind about it. It made the site look like a bowl of Froot Loops.

  5. …and as we all know, Froot Loops are bad for your teeth… they are also bad for your sugar levels, which, left unmonitored can lead to some scary diabetic results.

    Wise choice, Chris.