Reputation:
Ok, so I have the following simple code which changes the background color to red of a selected cell in a table. It works great.
CSS:
.fixture-table td.team.on {
background-color: red;
}
JS:
$(document).on('ready', function() {
// change the color to red on table when clicked
$('td').click( function() {
$(this).toggleClass('on');
});
});
What I'm looking to do is when the cell is clicked, change to red. If the same cell is clicked again then change to yellow. Then if clicked again, change to no background color, so to have three states.
Thanks
Upvotes: 1
Views: 2445
Reputation: 67207
CSS:
.redColor { background-color:red; }
.yellowColor { background-color:yellow; }
.noColor { background-color:#fff; }
JS:
$(document).on('ready', function() {
$('td').click( function() {
if($(this).hasClass('noColor')) {
$(this).removeClass('noColor').addClass('redColor');
}
else if($(this).hasClass('redColor')){
$(this).removeClass('redColor').addClass('yellowColor');
}
else{
$(this).removeClass('yellowColor').addClass('noColor');
}
});
});
Upvotes: 0
Reputation: 2049
I’d add a data attribute to save the current state. Then change the classes depending on this state.
$('td').click(function () {
var cell = $(this),
state = cell.data('state') || 'first';
switch (state) {
case 'first':
cell.addClass('red');
cell.data('state', 'second');
break;
case 'second':
cell.addClass('yellow');
cell.data('state', 'third');
break;
case 'third':
cell.removeClass('red yellow');
cell.data('state', 'first');
break;
default:
break;
}
});
CSS
.red {
background-color: red;
}
.yellow {
background-color: yellow;
}
Upvotes: 1