Combined Style-Changer/Random Header

Due to the comment from BlueCougar on the ‘Javascript Random Header Image’ snippet, I’m writing this snippet to combine the random header and the style changer.

First, you need to create image folders for each of your different styles. The folders are called ‘images’, ‘images1′, ‘images2′ and ‘images3′ for this example. The important part is the number appended to the folder name. This makes it easy to choose a set of images depending on the style chosen. Inside each folder, name the images ‘image1′, ‘image2′, ‘image3′ etc.

We then use the window.onload event to assign the following variables and event listeners as well as calling RandImg() for the first time.

JavaScript – window.onload

1
2
3
4
5
6
7
8
9
10
11
12
<script type="text/javascript">
window.onload = function() {
    header = document.getElementById('header');
    head = document.getElementsByTagName('head')[0];
    pictures = new Array('images/image1.jpg','images/image2.jpg','images/image3.jpg','images/image4.jpg','images/image5.jpg');
    numPics = pictures.length;
    document.getElementById('style1').onclick = function(evt) {changeStyle(1);};
    document.getElementById('style2').onclick = function(evt) {changeStyle(2);};
    document.getElementById('style3').onclick = function(evt) {changeStyle(3);};
    RandImg();
}
</script>

Note that we set the pictures array to reference the ‘images’ folder. This only applies when the default style is used; it will be changed dynamically when the user changes style.

Next we have the RandImg() function. This is a stripped down version of our previous RandImg() function. I’ve left in the setTimeout which changes the image every 2 seconds to save you from reloading the page to see the various imagesbut you will probably want to remove it.

JavaScript – RandImg()

1
2
3
4
5
6
7
8
function RandImg() {
    clearTimeout(this._timer);
    if (document.images) {
        var chosenPic = Math.floor((Math.random() * numPics));
        header.style.background = 'url(' + pictures[chosenPic] + ')';
    }
    this._timer = setTimeout(RandImg,2000);
}

Finally, we have the amended changeStyle() function

JavaScript – changeStyle()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function changeStyle(stylenum) {
    var switcher = document.getElementById('switcher');
    pictures = 'images/image1.jpg,images/image2.jpg,images/image3.jpg,images/image4.jpg,images/image5.jpg';
    pictures = pictures.replace(/images/g, 'images' + stylenum);
    pictures = pictures.split(",");
    if (switcher) {
	head.removeChild(switcher);
    }
    var link = document.createElement('link');
    link.setAttribute('id','switcher');
    link.setAttribute('rel','stylesheet');
    link.setAttribute('href','css/style' + stylenum + '.css');
    link.setAttribute('type','text/css');
    head.appendChild(link);
    RandImg();
}

The major changes to this function are the following lines:

3
4
5
	pictures = 'images/image1.jpg,images/image2.jpg,images/image3.jpg,images/image4.jpg,images/image5.jpg';
	pictures = pictures.replace(/images/g, 'images' + stylenum);
	pictures = pictures.split(",");

The first line resets the variable ‘pictures’ to a string referencing the original ‘images’ folder.
The second line searches the ‘pictures’ variable and replaces any occurrences of the word ‘images’ with ‘images’ + stylenum, which would result in ‘images1′ or ‘images2′ etc depending on the value of the ’stylenum’ parameter passed in to the function.
The third line uses the split() function to convert the string to an array which will be used by the RandImg() function.

And that’s about it. The html stays the same as before. When you look at the example below, you will notice that the images take a while to appear the first time round. This is down to my laziness (I haven’t optimised the images at all and consequently they are much larger than they need to be). Also, I apologise for the quality of the images used; this is just a quick example to show you that it works :)

You can see the example here

Feed IconFollow me on Twitter





10 Responses to “Combined Style-Changer/Random Header”

  1. This is really great. But I do have a small problem, I used this method, [ http://www.alistapart.com/articles/alternate/ ] in creating my style switcher it works well and has the cookie code so the pages stay in the same style…I don’t suppose you have a quick code snippet for enabling random headers that goes with this code?
    If it’s to much of a bother I’ll wait for when you add that javascript snippet on cookies, so I can use this nice code you’ve made. Thanks very much for adding this

  2. @BlueCougar
    I’ll have a look at the code you’re already using and see if I can integrate the random header for you.
    I’ll reply to this post with the results. :)

  3. OK, I’ve had a quick look. This should hopefully work.
    Inside your existing <script> tags, define a slightly modified randImg() function, like this:


    function randImg(folder) {
    var header = document.getElementById('header');
    var pictures = new Array('/image1.jpg','/image2.jpg','/image3.jpg','/image4.jpg','/image5.jpg');
    var numPics = pictures.length;
    var chosenPic = Math.floor((Math.random() * numPics));
    header.style.background = 'url(' + folder + pictures[chosenPic] + ')';
    }

    and then call the randImg() function from inside your existing setActiveStyleSheet() function like this:


    function setActiveStyleSheet(title) {
    var i, a, main;
    for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
    a.disabled = true;
    if(a.getAttribute("title") == title) a.disabled = false;
    }
    }
    randImg(title);
    }

    For this to work, you’ll need to name your image folders the same as the title attributes of your stylesheets. Hope that makes sense!
    Let me know how you get on :)

  4. I don’t know if it matters, but I don’t have the scripts right on my page, I link to them, for example:
    Besides that, I followed your instructions, and fixed my code but now on my test page the header and content images don’t show and the second style sheet refuses to work.
    [ http://www.freewebs.com/bluecougarstudio/styleswitcher.js ] here’s my .js page, I troubleshooted quite a bit, I don’t know if I did anything wrong…if I did I couldn’t find it.

  5. Hi, try changing your RandImg() function to the modified one in my last comment.
    Notice that the array ‘pictures’ doesn’t include the folder names, just the image names.
    The folder names are dynamically created to be the same as the ‘title’ attributes for the stylesheets. So, if your title is ‘lightson’, the RandImg() function searches for images in the /lightson folder. At the moment, I notice that your titles are in lowercase i.e. ‘lightson’ but your folder names use uppercase i.e. ‘LightsOn’. This won’t work so change your folder names to lowercase too.
    Once again, let me know how you get on.

  6. Oh wow I just realized that my scripts code snip didn’t show up in my last comment, sorry.
    Anyway, I fixed the code to be just like you said, all the titles are uppercase and the images don’t include folder names.
    But still no luck, it’s the same as before. The header image(s) won’t show, and the style switcher won’t work.
    This is the test page I’m seting it up on if you want to see,
    [ http://www.freewebs.com/bluecougarstudio/newlayout.html ]

  7. Hi, i’m using a style switcher from dynamic drive. I need to change my headers everytime my stylesheet changes, but not randomly. One style is called “Flame on”, so i need my flame header to show.

    Thanks in advance.

  8. Hi Fox,
    I’m not familiar with that script. I’ll download it and take a look, see if I can help.

  9. Hi, any progress with that request of mine? I just cant seem to figure it out myself.

    Fox

  10. It’s been 6 months and i still dont know how to do this style/header switcher thing. But thanks to all the people who tried to help.

    Fox

Leave a Comment







XHTML: You can use the following tags in your comments: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">