javascriptjquerycss

Can I disable a CSS :hover effect via JavaScript?


I’m trying to prevent the browser from using the :hover effect of the CSS, via JavaScript.

I have set the a and a:hover styles in my CSS, because I want a hover effect, if JS isn’t available. But if JS is available, I want to overwrite my CSS hover effect with a smoother one (using the jQuery color plugin for example.)

I tried this:

$("ul#mainFilter a").hover(
     function(e){ e.preventDefault(); ...do my stuff... }, 
     function(e){ e.preventDefault(); ...do my stuff... });

I also tried it with return false;, but it does not work.

Here is an example of my problem: http://jsfiddle.net/4rEzz/. The link should just fade without getting gray.

As mentioned by fudgey, a workaround would be to reset the hover styles using .css() but I would have to overwrite every single property, specified in the CSS (see here: http://jsfiddle.net/raPeX/1/ ). I am looking for a generic solution.

Does anyone know how to do this?

PS: I do not want to overwrite every style i have set for the hover.


Solution

  • There isn’t a pure JavaScript generic solution, I’m afraid. JavaScript isn’t able to turn off the CSS :hover state itself.

    You could try the following alternative workaround though. If you don’t mind mucking about in your HTML and CSS a little bit, it saves you having to reset every CSS property manually via JavaScript.

    HTML

    <body class="nojQuery">
    

    CSS

    /* Limit the hover styles in your CSS so that they only apply when the nojQuery 
    class is present */
    
    body.nojQuery ul#mainFilter a:hover {
        /* CSS-only hover styles go here */
    }
    

    JavaScript

    // When jQuery kicks in, remove the nojQuery class from the <body> element, thus
    // making the CSS hover styles disappear.
    
    $(function(){}
        $('body').removeClass('nojQuery');
    )