Stefan Dunn
Stefan Dunn

Reputation: 5513

Javascript style overriding CSS hover

To make this clearer, I'll use my code below:

I have a divider container, "c_container":

<div id="c_container">
<div id="c_tab">Menu</div>
<div id="c_main">MenuContent</div>
</div>

Then I have CSS that controls it's style:

#c_container {
    width: 550px;
    height: 265px;
    position: fixed;
    left: -550px;
    margin-left: 35px;
    top: 50%;
    margin-top: -100px;
}
#c_container:hover{
    margin-left: 0px;
    left: -40px;
}

Then after I update the style using Javascript from an onClick function:

function hideForm(){
    var msg = document.getElementById("c_container");
    msg.style.left = "-550px";
}

The CSS hover only effects the margin property and doesn't effect the left property as it did before. It's like javascript has locked it.

Upvotes: 1

Views: 5591

Answers (4)

Jones
Jones

Reputation: 1500

Have problem with commas in onclick function ...

onclick="document.getElementById('div').style.left='-550px;'"

and 'div' is not good name for id.

Your CSS is confusing. For apply DIV tag

div {
   position: fixed;
   left: -550px;
}
div:hover{
   left: 0px;
}

OR

#DIV_ID { ... } 

OR

.CLASSNAME { ...} 

EDIT

I'm recriate your example ... http://jsfiddle.net/PAg9M/1/ and work for me. What you need?

Upvotes: 1

NewUser
NewUser

Reputation: 287

You are facing this problem because inline css haves more priority than the one in"style" tag and javascript add inline css.

So should use only javascript to do this-

modify your html-

<div id="c_container" onmouseover="style.left='0'" onmouseout="style.left='-550'">
<div id="c_tab">Menu</div>
<div id="c_main">MenuContent</div>
</div>

This will sort out your problem.

Upvotes: 0

John Lawrence
John Lawrence

Reputation: 2923

Styles added with the JavaScript style are creating an inline style which has higher precedence than your style sheet. To fix this you can add !important to your style sheet:

#c_container:hover{
    margin-left: 0px;
    left: -40px !important;
}

Upvotes: 2

Hidde
Hidde

Reputation: 11961

jQuery:

//Normal: 
$('elementNameOrID').hover (function () {
    $(this).css('left', 0);
}, function () {
    $(this).animate('left', -500);
}); 

//Nice:
$('elementNameOrID').hover (function () {
    $(this).animate({left: 0});
}, function () {
    $(this).animate({left: -500});
}); 

JS:

onclick = function () {
    document.getElementById("div").style.left = '-550px';
};

Sidenote: Using div as a name for an element is NOT a good idea and very confusing and misleading when reading your code.

Upvotes: 3

Related Questions