I have an element, when clicked, would check the class of a different element.
If it has a specific class, it’ll remove it, and replace it with a different class.
Again, if clicked, it’ll reverse that process with the swapped class name.
(to give a visual, the class is a lovely Star Icon, and it’s shaded version)
I think my code below is a little too verbose.
Can anyone see a better/shorter way to state it?
<script language="javascript" type="text/javascript">
$(document).ready(function(){
$(".clickme").click(function(){
if($("#staricon").hasClass("starON")){
$("#staricon").removeClass("starON").addClass("starSHADED");
}else if($("#staricon").hasClass("starSHADED")){
$("#staricon").removeClass("starSHADED").addClass("starON");
}
});
});
</script>
Also, starON and starSHADED are part of a sprite.
The code above works! But I’m sure it can be optimized.
I see jQuery has a .toggleClass() API, and I’m running into swapping the two classes incorrectly.
1 Answer