Dimitri Vorontzov
Dimitri Vorontzov

Reputation: 8104

Cancel CSS hover behavior with jQuery

The website I work on has a navigation menu (a CSS-formatted unordered list) with sub-menus for some of the categories (children unordered lists).

This CSS rule hides a submenu unordered list:

.main-navigation ul ul {
    display:none;
}

And this CSS rule makes submenu unordered list appear when a visitor hovers the cursor over the top level menu link:

.main-navigation ul li:hover > ul {;
    display:block;
}

This is done for those (possibly non-existent) users who have JavaScript disabled in their browsers.

Now I'm spicing up that navigation menu with jQuery, and the very first thing that I need to do is disable the on hover behavior, dictated by CSS. For some reason I'm having hard time doing so, and could use some help. Here's what I tried:

jQuery(document).ready(function($) {
     $('.main-navigation ul li:hover > ul').css('display', 'none');

});

No luck, CSS still controls the behavior, and the submenu pops up on hover, as if there's no jQuery present. Which means, I'm not doing it correctly.

I'd appreciate it if someone explained to me how this should be done!

Upvotes: 3

Views: 988

Answers (2)

A. Wolff
A. Wolff

Reputation: 74420

Try this:

DEMO

jQuery(document).ready(function($) {
     $('.main-navigation ul li').on('mouseover',function(){
        $('.main-navigation ul li:hover > ul').css('display', 'none');
     });
});

Upvotes: 3

techfoobar
techfoobar

Reputation: 66693

The best you can do is remove the main-navigation class from the parent. Otherwise, you cannot manipulate the styles of pseudo classes from JavaScript.

Upvotes: 3

Related Questions