Reputation: 2040
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
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
Reputation: 22323
use parseInt
to compare with case.With this its unable to compare.See fiddle.
http://jsfiddle.net/cF74Y/43/
Upvotes: 0
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
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.
Upvotes: 3
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