It has to do with the order in which the CSS rules are defined.

.divRed and .divGreen have the same level of specificity (a 1 in the "tens" column), so an element <div class="divRed divGreen"></div> will have a green background if .divGreen is defined after .divRed, but it will have a red background is .divRed is defined after .divGreen. In your <style> element, .divGreen is defined last, so that is what gets priority.

If you wanted to toggle between green and red, you could try this:

$(".divGreen").click(function() { $ (this).toggleClass("divRed").toggleClass('divGreen'); });

Or, you could just give "divRed" style definition a higher level of specificity (which would require giving "divGray" the same level of specificity to avoid messing up the first test.):

<style>
        div {height: 100px; width: 100px;}
        div.divRed  {background-color: red;}
        div.divGray  {background-color: gray;}
        .divGreen  {background-color: green;}
</style>


Hope that helps.

--Karl

On Feb 8, 2008, at 8:40 AM, meeboo wrote:



Hey all!

I'm wondering why the following code will toggle the div 'divRed' to a
different color, but it won't toggle the color for 'divGreen'.

<style>
        div {height: 100px; width: 100px;}
        .divRed  {background-color: red;}
        .divGray  {background-color: gray;}
        .divGreen  {background-color: green;}
</style>
<script type="text/javascript">
        $(document).ready(function() {
        $(".divRed").click(function() {  $(this).toggleClass("divGray"); });
        $(".divGreen").click(function() {  $(this).toggleClass("divRed"); });
});
</script>
</head>
<body>
        <div class="divRed">test</div> <!-- Toggles background color -->
<div class="divGreen">test 2</div> <!-- Will not toggle background
color -->
</body>

The odd thing is that when I inspect the divs they both are updated by
jQuery and their classes are toggled, but the background color change will
only be for divRed and not divGreen
--
View this message in context: 
http://www.nabble.com/toggleClass-weird-behaviour-tp15350732s27240p15350732.html
Sent from the jQuery General Discussion mailing list archive at Nabble.com.


Reply via email to