Bobe
Bobe

Reputation: 2040

JavaScript switch for changing background colour with css()

I have a very simple function which should change the page background colour based on specific links being clicked, but I can't figure out why it's not working.

Here is a demo of what I have so far: http://jsfiddle.net/cF74Y/

It seems like it must be such a trivial mistake, but I can't see it. Any help would be greatly appreciated.

Upvotes: 1

Views: 2580

Answers (6)

elclanrs
elclanrs

Reputation: 94121

I think you're complicating things too much, can't you just do this?

html:

<ul id="nav">
    <li><a class="color" href="#">red</a></li>
    <li><a class="color" href="#">green</a></li>
    <li><a class="color" href="#">blue</a></li>
    <li><a class="color" href="#">yellow</a></li>
</ul>

jQuery:

$('a.color').click(function(){
    $('body').css('background-color', $(this).text());
});

Demo: http://jsfiddle.net/elclanrs/8yev9/

Edit: And if you need to assign a color by index use an array, I don't think you need that ugly switch statement, seems pretty useless to me, all that code can be reduced to just this:

var colors = ['red', 'blue', 'green', 'yellow'];
$('a.color').click(function(){
    $('body').css('background-color', colors[$(this).parent().index()]);
});

Demo: http://jsfiddle.net/elclanrs/8yev9/1

Upvotes: 3

4b0
4b0

Reputation: 22323

use parseInt to compare with case.With this its unable to compare.See fiddle. http://jsfiddle.net/cF74Y/43/

Upvotes: 0

MaVRoSCy
MaVRoSCy

Reputation: 17839

here is a working copy

http://jsfiddle.net/cF74Y/34/

Upvotes: 0

yoku2010
yoku2010

Reputation: 600

try this:

var index = parseInt($(this).attr('id'),10);

then it will work.

Reason: the return type of .attr() function is a string and it make true case 1 always. just use parseInt function.

Upvotes: 2

xdazz
xdazz

Reputation: 160883

You are compare string with number, change switch (currentItem) to switch (+currentItem) will make your demo work.

Addition: You could pass the currentItem as a parameter instead of using global variable.

Here is the working demo.

Upvotes: 3

Lea
Lea

Reputation: 363

Maybe you have to give the parameter 'currentItem' with the function call.

changeBg(currentItem); // call

And your function will look like this:

function changeBg(currentItem) {
    var bg = 'null';
    switch (currentItem) {
        case 1 :
            bg = '#6A6A6A';
[..]

Upvotes: 0

Related Questions