September 5, 201115 yr Hello Friends JSFiddle have made things so much easier ! Here's a link. What I want to achieve is an alternation between two states. So user clicks once, the box goes Yellow, the user clicks a second time, the box goes back to Red, and the effect to repeat. I don't know how to do that and I would greatly appreciate some help. Thank You. Edited September 5, 201115 yr by Ciwan
September 6, 201115 yr <style type="text/css"> .red { background-color: red; } .yellow { background-color: yellow; } </style> <script type="text/javascript"> $(document).ready(function(){ $('#click').click(function(){ if($(this).hasClass('red')) { $(this).removeClass('red').addClass('yellow'); } else { $(this).removeClass('yellow').addClass('red'); } }); }); </script> <div id="click" class="red"></div>
September 6, 201115 yr Author Huh soo simple ! Thanks Skidz. Is there a way to do it without adding the extra CSS ? Thank You.
September 6, 201115 yr There is but tbh it would be more messy than this. Surely adding a couple of css classes to your stylesheet isn't that much of an issue?
September 6, 201115 yr Author No It isn't an issue at all, I was just wondering if the other way was neater .. I care about neat code. But you're saying it'll be more mess .. in which case leave it. Thanks once again.
September 6, 201115 yr I always advocate that using .css() is terrible! You should always create style rules in the stylesheet not via javascript. Real world scenario: Say I come to your project in 6 months time because you've asked me to update something. I need to change the colour of the box. I would immediately be looking for style rules so I'd instantly go to the stylesheet.
September 6, 201115 yr Nice. The only comment is to use some sort of identifier an your anchor tag (<a>) as your current selector will match any anchor on the page.
September 6, 201115 yr Author Yep will do. This was just a JSFiddle for you guys to help me. On the real site, I'll have to be much more specific with the selectors. Thanks for all the help.
Create an account or sign in to comment