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.
To remove the CSS hover effect from a specific element, you can set the pointer-events property of the element (the hover behavior of which you want to disable) to “none”.
One method to do this is to add: pointer-events: none; to the element, you want to disable hover on. (Note: this also disables javascript events on that element too, click events will actually fall through to the element behind ).
You can remove all the CSS rules containing :hover using Javascript. This has the advantage of not having to touch CSS and being compatible even with older browsers. Limitations: stylesheets must be hosted on the same domain (that means no CDNs).
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.
<body class="nojQuery">
/* 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 */ }
// When jQuery kicks in, remove the nojQuery class from the <body> element, thus // making the CSS hover styles disappear. $(function(){} $('body').removeClass('nojQuery'); )
Use a second class that has only the hover assigned:
HTML
<a class="myclass myclass_hover" href="#">My anchor</a>
CSS
.myclass { /* all anchor styles */ } .myclass_hover:hover { /* example color */ color:#00A; }
Now you can use Jquery to remove the class, for instance if the element has been clicked:
JQUERY
$('.myclass').click( function(e) { e.preventDefault(); $(this).removeClass('myclass_hover'); });
Hope this answer is helpful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With