Alternate colors on click with jQuery
Posted
by
Jace Cotton
on Stack Overflow
See other posts from Stack Overflow
or by Jace Cotton
Published on 2014-05-26T21:08:48Z
Indexed on
2014/05/26
21:26 UTC
Read the original article
Hit count: 191
I'm sure there is a simple solution to this, and I'm sure this is a duplicate question, though I have been unable to solve my solution particularly because I don't really know how to phrase it in order to search for other questions/solutions, so I'm coming here hoping for some help.
Basically, I have span
s with classes that assigns a background-color
property, and inside those span
s are words. I have three of these spans, and each time a user clicks on a span I want the class to change (thus changing the background color and inner text).
HTML:
<span class="alternate">
<span class="blue showing">Lorem</span>
<span class="green">Ipsum</span>
<span class="red">Dolor</span>
</span>
CSS:
.alternate span { display : none }
.alternate .showing { display : inline }
.blue { background : blue }
.green { background : green }
.red { background : red }
jQuery:
$(".alternate span").each(function() {
$(this).on("click", function() {
$(this).removeClass("showing");
$(this).next().addClass("showing");
});
});
This solution works great using $.next
until I get to the third click, whereafter .showing
is removed, and is not added since there are no more $.next
options. How do I, after getting to the last-child
, add .showing
to the first-child
and then start over? I have tried various options including if($(".alternate span:last-child").hasClass("showing")) { etc. etc. }
, and I attempted to use an array
and for loop
though I failed to make it work.
Newb question, I know, but I can't seem to solve this so as a last resort I'm coming here.
© Stack Overflow or respective owner