0

I came across an example of revealing a hidden div which is inside an element using css only

<style type="text/css">
#shopCart:hover .shopCartDetail {
    display: block;
}
</style>

<div id="shopCart">
Shop Cart
<div class="shopCartDetail"><style>.shopCartDetail {display:none}</style>
    This is Shop Cart Detail</div>
</div>

Working example here http://jsfiddle.net/7DRTD/

In my scenario, the style display:none is created by jQuery. Revealing the hidden div using hover does not work: http://jsfiddle.net/Z2mtF/

What can be the issue here? The html code looks same, both examples add inline style to the div.

The question is: why does the second scenario not work?

Thank you.

7
  • 1
    You posted the same JSFiddle twice. Commented Nov 30, 2012 at 0:20
  • I didn't quite understand your problem but if you're talking about jQuery hover and you're dynamically creating that object, you should use "live" instead of "hover" so when the object is created, the live event will bind to it. Commented Nov 30, 2012 at 0:23
  • Why have you got the separate <style> block inside your <div>? You know you can define both settings in the same block: jsfiddle.net/7DRTD/5 Doing it with jQuery also works: jsfiddle.net/7DRTD/6 Commented Nov 30, 2012 at 0:25
  • @vucko sorry, it should be now ok Commented Nov 30, 2012 at 0:26
  • @nnnnn I used <style> to emulate inline class Commented Nov 30, 2012 at 0:28

1 Answer 1

2

In a general sense, styles applied directly to an individual element take precedence over settings from the stylesheet. This is (part of) the "cascading" effect that is the "C" in "CSS". So when you hide the element with jQuery with the following in your document ready:

$(".shopCartDetail").css("display","none");

...it is equivalent to adding style="display:none" directly to the element, which has the same "problem": http://jsfiddle.net/Z2mtF/2/

This is not the same as applying a class to the element, which is what your "emulation" above was doing with the <style> element inside the <div>.

So the hover rule isn't important enough to take effect. One way to fix this is to make the hover rule important:

#shopCart:hover .shopCartDetail
{
    display: block !important;
}

Demo: http://jsfiddle.net/Z2mtF/1/

Settings in the stylesheet marked as !important will take precedence over the inline style attributes.

Note that it's tidier if you use .show() and .hide() instead of explicitly setting the display property via the .css() method.

Sign up to request clarification or add additional context in comments.

Comments

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.