1

I have a sidebar menu, and using js code active item has different background and font color. It works, but after clicking on any item, css line marked bellow as line x - doesn't more work. Why is it lost. In js code I didn't touch :hover state at all ?

<div id="divL">
<div id="sky">SKY</div>
<div id="sea">SEA</div>
<div id="universe">UNI-VERSE</div>
</div>  

css

#divL  div{
    margin:3px 0;
    padding:5px 14px;
    cursor:pointer;
}
#divL div:first-of-type {
  background:#ffffff;
    color:#008080;
}
#divL div:hover{  // line x
    background:#ffffff;
    color:#008080;
}

JS

$("#divL div").click(function () {
$('#divL div').css({'background':'#008080', 'color':'#ffffff'})
$(this).css({'background':'#ffffff', 'color':'#008080'})
});
0

1 Answer 1

3

Your jQuery code is changing the inline style and it is overwriting your CSS file styles.

As pointed out in the documentation:

When using .css() as a setter, jQuery modifies the element's style property.

Your code results in:

<div id="universe" style="background-color: #fff; color: rgb(0, 128, 128); background-position: initial initial; background-repeat: initial initial;">UNI-VERSE</div>

I would recommend you to use another style instead of changing the inline styles with jQuery. You can make use of addClass(), removeClass() or even the toggleClass() functions of jQuery.

Living demo: http://jsfiddle.net/uUDeS/1/

jQuery:

$("#divL div").click(function () {
    $(this).siblings().removeClass('active').addClass('inactive');
    $(this).addClass('active')
});

CSS:

#divL div.inactive {
    background:#008080;
    color:#fff;
}
#divL div.active {
    background:#fff;
    color:#008080;
}
Sign up to request clarification or add additional context in comments.

8 Comments

Alvaro, thanks I'll try with toggleClass() but I don't understand why is hover state changed. There is no such a line in js code
@SunSky the hover state isn't changed - it's still being applied, but it's being overridden by the inline styles applied.
xdumaine, why is it overridden ? Where is such instruction in js code ? There is no :hover state line in js.
Inline style override embedded styles. It has a higher specificity. The inline styles applied are more important than the :hover style.
Moob, where is js line to change hover state ? It doesn't exist !
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.