neda Derakhshesh
neda Derakhshesh

Reputation: 1163

toggleClass in jquery dosent work when i use id selector in Css

I'm new at jQuery and I have a problem that when I use ID selector in CSS then my jQuery code doesn't work.

Here is HTML:

<body>    
    <div id="fm">
    </div>
</body>

Here is JavaScript Code:

$(function () {
    $("#fm").click(function () {
        $(this).toggleClass("cm");
    });
});

This CSS is OK and it works:

body>div{ 
    height:100px;
    background-color:blue;
    transition:all ease 0.5s;
    position:fixed;
    top:0;
    left:0;
    bottom:100px;
    right:0;
    z-index:1000;
}

But if I use #fm in CSS selector it doesn't work. I think it may be because of cascading behavior but I don't know how to fix it.

Here is the CSS which doesn't work:

#fm{ 
    height:100px;
    background-color:blue;
    transition:all ease 0.5s;
    position:fixed;
    top:0;
    left:0;
    bottom:100px;
    right:0;
    z-index:1000;
    border:1px solid black;
}

And this is cm class

.cm {
    background-color:red;
    height:150px;
}

I appreciate if you help

Upvotes: 2

Views: 321

Answers (3)

Sudharsan S
Sudharsan S

Reputation: 15393

Id have high priority in css so your .cm class be override with id #fm

Use !important only work in the context

.cm
{
    background-color:red !imporatnt;
    height:150px;
}

Upvotes: 2

Tushar
Tushar

Reputation: 87203

toggleClass is working, but the css properties are not applied.

You need to use !important to override proeperties.

.cm {
    background-color:red !important;
    height:150px;
}

Demo: https://jsfiddle.net/tusharj/ecojmyje/

Upvotes: 2

Ben Philipp
Ben Philipp

Reputation: 1877

Try

#fm.cm

for your cm rule. This way, the ID doesn't override the class

Upvotes: 7

Related Questions