Check out my fiddle here
Here is the js in question:
$(document).ready(function() {
$('.clickMe').toggle(
function() {
$('#coloredDiv').css({
"background-color": "#eeeeee"
})
}, function() {
$('#coloredDiv').css({
"background-color": "#00ff00"
})
}, function() {
$('#coloredDiv').css({
"background-color": "#ff0000"
})
}, function() {
$('#coloredDiv').css({
"background-color": "#000000"
})
});
});
The goal: each time the link is clicked ("click me") the background color of the #coloredDiv should change to one of the following colors in the order provided: #eeeeee, #00ff00, #ff0000, #000000 . Once the last color is reached, if the link is clicked again, the cycle should start over from the first color listed.
The code works but I would like to know: is the code in its current form respectable or is it not so good? Am I making poor choices? What other way could this be written to achieve the same result but in perhaps a slightly better (i.e. more elegant) way?
Lastly, you'll notice that upon page load the square has no default color. I've toyed with the idea of defaulting to #eeeeee upon load but I realize that I would then need to account for this using a conditional statement to check the current color and then apply the appropriate color depending on the situation. Any guidance on how to approach writing this would be greatly appreciated.
Please note that I want to accomplish this task using only jQuery and no plugins.
Thanks for the help.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…