July 15, 2012

jQuery hide + CSS hover issue with mouse

Question by Xander Guerin

Has anyone else noticed that when you have the CSS:hover effect applied to an element, hide that element and keep the mouse perfectly still, the hover effect is still present until the mouse moves?

I’ve has a search but can’t seem to find any other threads similar. I know it is probably easy but I cannot find the solution and it will cause me to end up in Bedlam.

To see what I mean, take a look at this Fiddle: http://jsfiddle.net/NsMKN/ and

  1. Click the black box to expand it
  2. move the cursor outside the original blackness like where the red X is
  3. click to hide and keep the mouse cursor PERFECTLY still
  4. notice the black box is still red???

When the cursor moves, the :hover is not applied as it should, but it there a way to do this without having to move the mouse and without having to apply the hover effect using jQuery myself (leaving it to CSS)?

Update: I’ve marked Starx as the answer as it does appear to be an IE thing. Thanks for the help guys.

awesome piccy

Answer by Starx

Let me split your code.

<div class="tester">
    <div class="content">
        apple, banana, carrot, lettuce, celery, beetroot
    </div>
</div>

Here, the div .content is inside .tester which wraps itself with respect to the what is inside, on general cases.

.tester:hover
{
   background-color:red; 
}

Your CSS is also applied to the same wrapper div i.e. .tester. So, that when the mouse is over to this part, its background color will change.

$('.tester').click(function () {
    $(this).children('.content').toggle();
});

Now, when you toggle the inner element to make it visible. The dimensions of the .tester will change according to the inner elements. Although it is fixed in your case, DOM also has to consider its children. Try to do the same with this fiddle.

Example Showing the Issue

Due to this reason The the mouse will still be over the div .tester. So, style of .tester:hover will still be applied.

Now, when you the toggle .content, the wrapper div .tester will retain the previous state, until further event occurs.

Browsers like IE, does not seem to update its DOM properties until next event occurs.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!