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: /
It seems like it must be such a trivial mistake, but I can't see it. Any help would be greatly appreciated.
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/cF74Y/
It seems like it must be such a trivial mistake, but I can't see it. Any help would be greatly appreciated.
Share Improve this question edited Oct 4, 2012 at 7:04 Bobe asked Oct 4, 2012 at 6:31 BobeBobe 2,0408 gold badges30 silver badges50 bronze badges 3- 1 Add your code here. Some people may not have access to Fiddle – Murali Murugesan Commented Oct 4, 2012 at 6:31
- 2 Stop trying to rollback my changes, code should be part of the question. – Ja͢ck Commented Oct 4, 2012 at 6:48
- @Jack I thought they were changes I made and forgot to delete. – Bobe Commented Oct 4, 2012 at 7:05
6 Answers
Reset to default 3You are pare 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.
I think you're plicating 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/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/elclanrs/8yev9/1
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.
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';
[..]
here is a working copy
http://jsfiddle/cF74Y/34/
use parseInt
to pare with case.With this its unable to pare.See fiddle.
http://jsfiddle/cF74Y/43/