views:

247

answers:

5

I want to make a CSS style switcher in JavaScript, same as digg.com does here: http://digg.com/add-digg

I am having a div, in which I want to change the style of the div box on the basis of theme selection. Please give me any link or code, how I can do this.

I don't want to use Jquery, I want to develop this cod ein pure javascript.

Thanks

A: 

Its quite simple really, the user chooses a color (#544856) then you use the onchange event or similar and do:

 document.getElementById("myDiv").style.color = 
       document.getElementById("myColorTextBox").value;
ck
A: 

The easiest way would be to create 2 style sheets, with the same classes in them, but with different colors etc. Then allow the users to switch between them, here's a link to an example:

example

Colin
I already have different style-sheet files for my themes. But my theme files are different and my main html page css file is different, so the example which you have given changes the stylesheet for the whole page, whereas I want to change the style of only a single DIV element?
Prashant
really only one element? if so the optimal solution is to change the class of the div, but the more detached and flexible solution is to enable/disable whole stylesheets.
annakata
+9  A: 

Inspecting the source code and how it changes as you change themes, it is really quite simple. Digg is harnessing the awesomeness of CSS to drastically change content by simply changing the class of an element. All you have to do is this:

<div id="theme_viewer">
<!-- HTML code for your widget/thing to be styled -->
</div>

And then you can have your themes:

<ul>
  <li><a href="#" onclick="return switchTheme('theme1');">theme 1</a></li>
  <li><a href="#" onclick="return switchTheme('theme2');">theme 2</a></li>
  <li><a href="#" onclick="return switchTheme('theme3');">theme 3</a></li>
  <li><a href="#" onclick="return switchTheme('theme4');">theme 4</a></li>
</ul>

All switchTheme needs to then do is change the class of theme_viewer to the class passed:

function switchTheme(theclass) {
    var viewer = document.getElementById('theme_viewer');
    viewer.className = theclass;
    return false;
}

Your CSS stylesheets can then do whatever the different styles call for:

#theme_viewer.theme1 {
    background-color: red;
}

#theme_viewer.theme2 {
    background-color: blue;
}

#theme_viewer.theme3 {
    background-color: black;
    color: white;
}

#theme_viewer.theme4 {
    background-color: orange;
}

here is an example of this at work

As mentioned in the comments by J-P and in edeverett's answer, it is not a good idea to have your events inline as I have them in this example (ie, with the onclick attribute). I did it for simplicity, but it's not a good idea. The better idea is to wait for your document to load and attach the event handlers dynamically with Javascript. This is known as unobtrusive Javascript, and it is a Good ThingTM.

An example of the above example following good practices would look like this:

<ul id='theme_options'>
  <li><a href="#" id='theme1'>theme 1</a></li>
  <li><a href="#" id='theme2'>theme 2</a></li>
  <li><a href="#" id='theme3'>theme 3</a></li>
  <li><a href="#" id='theme4'>theme 4</a></li>
</ul>

And then we use this cross browser addEvent function (written by John Resig, author of jQuery):

function addEvent( obj, type, fn ) {
  if ( obj.attachEvent ) {
    obj['e'+type+fn] = fn;
    obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
    obj.attachEvent( 'on'+type, obj[type+fn] );
  } else
    obj.addEventListener( type, fn, false );
}

To add the event handlers:

addEvent(window, 'load', function() {
    var opts = document.getElementById('theme_options');
    var links = opts.getElementsByTagName('a');
    for(var x = 0; x < links.length; x++) {
        addEvent(links[x], 'click', function() {
            switchTheme(links[x].id);
        });
    }
});

It might be a little more verbose than inline Javascript, but it is worth it. I know you said you'd like to avoid jQuery, but something as simple as this makes you start appreciating the library, as you could do it with jQuery with something as simple as this:

$(function() {
    $('a','#theme_options').click(function() {
        switchTheme($(this).attr('id'));
        return false;
    });
});
Paolo Bergantino
+1 for this good explanation :)
Prashant
+1 as always Paolo. One thing though: I realise that it may be easier to teach with inline event handlers but it's no longer considered the right way of doing things. Respectfully, please use unobtrusive event handling.
J-P
J-P: as I said in the comments in edeverett's answer - I am fully aware of this, obviously. I put them in there for this example in the interest of keeping it simple. I will add a note on best practices, though. Thank you.
Paolo Bergantino
A: 

This might help you: "Dynamically loading an external JavaScript or CSS file"

So when the user clicks your theme change button, the onclick event loads an external CSS file.

Might be easier/faster with jQuery though. You'll also need to store a variable to indicate that the user has selected a different theme.

Chris Cooper
+1  A: 

There's three parts to this:

1) The div itself This stays almost the same for all styles. The Javascript will only change the class attribute to change the styles that the CSS applies to the div. Create the div so that it has the default style when the page is created and add an id so we can get at it easily with Javascript later:

<div class="style1" id="styleBox"></div>

2) The CSS In your CSS you need to have a class for each way you want the div presented. Set up all the generic attributes like width and height first in one style rule:

.style1,
.style2,
.style3 {widht:200px; height:400px; text-size:1em;}

Then set up the rules for the individual styles:

.style1 {background-color:aqua;} .style2 {background-color:yellow;} .style3 {background-color:pink;}

Note that these are all in the same stylesheet, this will make it easier to manage.

3) The Javascript This is where you add the behaviour. You'll also need some links to click, ideally these should be created with JS as they aren't any use to the user without it - but for now lets assume they are in the page:

<div id="styleMenu">
  <a href="#" id="style1" >Style 1</a>
  <a href="#" id="style2" >Style 2</a>
  <a href="#" id="style3" >Style 3</a>
</div>

You'll need to have a JS function that is run when the page loads (google "javascript onload function"). In this function you'll need to get a reference to the div containing the links and add a onClick event to in. This event will get fired when the links get clicked - this is called Event Delegation (google it). In this event function you'll need to find out which link has been clicked using the event.target (or event.srcElement for IE). Then set the className property of the styled div to the id of the link that was clicked.

I'll leave writing the actually JS to you, but if you use this slightly longer way of doing things - and not using inline styles or javascript - you have cleanly seperated HTML, CSS and Javascript which will make maintaining everything a lot easier.

edeverett
Oh, and using the Id attribute on the links also gives you the right hooks with which to apply the styles to the links so the user knows what they are getting.
edeverett
Even though this answer is basically what I said, +1 for mentioning inline js is a bad idea. I threw it in there for my example for the sake of simplicity but it is definitely best to keep your javascript unobtrusive.
Paolo Bergantino
Our answers are much the same, I'm probably a slower typist :-)
edeverett