djmzfKnm
djmzfKnm

Reputation: 27185

How to create a DIV style switcher?

I want to make a CSS style switcher in JavaScript, same as Digg does here

image from web archive, see summary for more details

I am having a div, in which I want to change the style of the div box on the basis of theme selection.

I don't want to use jQuery, I want to develop this code in pure JavaScript.

Upvotes: 1

Views: 921

Answers (5)

Paolo Bergantino
Paolo Bergantino

Reputation: 488394

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;
    });
});

Upvotes: 11

edeverett
edeverett

Reputation: 8218

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.

Upvotes: 1

Christopher Cooper
Christopher Cooper

Reputation: 1920

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.

Upvotes: 0

Colin
Colin

Reputation: 10638

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

Upvotes: 0

cjk
cjk

Reputation: 46425

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;

Upvotes: 0

Related Questions