Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery addClass has no effect

I have this html:

<div class="container">
    <div id="cell1" class="cell"><div class="content"></div></div>
    <div id="cell2" class="cell"><div class="content"></div></div>
    <div id="cell3" class="cell"><div class="content"></div></div>
</div>

CSS:

.container {
    width: 300px;
    height: 300px;
    background-color: green;
}

.cell {
    background-color: red;
}

#cell1 {
    width: 70px;
    height: 70px;
}

#cell2 {
    width: 70px;
    height: 70px;
}

#cell3 {
    width: 70px;
    height: 70px;
}

.white {
    background-color: white;
}

.yellow {
    background-color: yellow;
}

.content {
    width:40px;
    height:40px;
    background-color:blue;
}

Javascript:

$(document).on('click', '.cell', function(e) {

    $(this).parent().children().removeClass('white');
    $(this).parent().children().children().removeClass('yellow');

    $(this).addClass('white');
    $(this).find('.content').addClass('yellow');
});

The problem I am having now is addClass('yellow') has no effect. However, if I delete the background-color in content class, it works. Any thoughts why?

jsFiddle link: http://jsfiddle.net/rexwang/FWh6E/

Thanks for the answers, it works! But I really don't like using addClass and removeClass, is it posible to use e.currentTarget.id to achieve the same goal?

like image 219
Rex Avatar asked Dec 21 '22 05:12

Rex


2 Answers

It works but the .yellow background style is overriden by the .content background style, since in the stylesheet .content class goes after .yellow.

One way is to swap these classes in the CSS.

DEMO: http://jsfiddle.net/FWh6E/2/

like image 168
VisioN Avatar answered Dec 22 '22 19:12

VisioN


The .addClass() is working but because of the way CSS rules are applied, the .content selector has more weight than the .yellow single class selector - see CSS specificity for a Star Wars themed explanation of specificity.

In the CSS documentation the final clause is being used to determine which rule is applied.

Finally, sort by order specified: if two declarations have the same weight, origin and specificity, the latter specified wins. Declarations in imported style sheets are considered to be before any declarations in the style sheet itself.

So you could either swap the order of the rules in the CSS file, moving .yellow after .content, or give the .yellow selector more weight by adding another selector to the chain, for example:

.content.yellow {
    background-color: yellow;
}
like image 39
andyb Avatar answered Dec 22 '22 20:12

andyb