1

I'm creating an Avatar designer, where users can customize things like hairstyles & hair colours from a preselection.

It is basically a form with radio buttons that can be used to customize the avatar.

My form is wrapped in a DIV that has three classes:

<div id="container" class="hair-blonde skin-pink boy">

I need the classes to take the values of the radio buttons. So if a user clicks on a hair colour, the value of the hair colour radio button will overwrite the hair-blonde class.

I can't use ToggleClass or addClass because these don't give you control over which class is changed. Also, if hair-blonde changes to hair-red, then the script wont work anymore as it will still be looking for hair-blonde.

I thought I could use split to turn the list of classes into an array. However, when I try to swap the classes nothing happens.

Here is the code I am using:

$(".skincolour input").click(function(){
var newskincolour = $(this).val();
var skin_colour = $('#container').attr('class').split(' ')[1];
var skin_colour = newskincolour;
});

I have also tried this as a variation:

$(".skincolour input").click(function(){
var newskincolour = $(this).val();
var skin_colour = $('#container').attr('class').split(' ')[1];
var skin_colour = $(".skincolour input").val();
});

Could someone give me some pointers as to what I am doing wrong?

Community
  • 1
  • 1
big_smile
  • 1,487
  • 4
  • 26
  • 59

2 Answers2

1

Your approach could work, but you forgot to overwrite the element's class attribute. Try this:

$(".skincolour input").click(function(){
    var newskincolour = $(this).val();
    var classes = $('#container').attr('class').split(' ');
    classes[1] = newskincolour;
    $('#container').attr('class', classes.join(' '));
});
bfavaretto
  • 71,580
  • 16
  • 111
  • 150
0

you may use removeClass to remove the classes of the same category, followed by addClass.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • I don't understand. Lets say I tell Jquery to remove .hairblonde and add .hairred. Well, when the user clicks on a different colour, the script wont work as .hairblonde no longer exists. – big_smile Sep 28 '12 at 14:27
  • You may remove classes that aren't present. So you may do `.removeClass('.hairblonde').removeClass('.hairbrown').addClass('.hairred');` – Denys Séguret Sep 28 '12 at 14:28
  • Thanks for your help. bfavaretto's solution is slightly better as less code writing is required. However, your is still a good idea! Thanks again! – big_smile Sep 28 '12 at 14:55