Conflict between jQuery.css () and CSS hover property

Basically I have 3 links, and I used the hover css property to make them white / red when the user enters / leaves the link:

<div id="nav-glob"> <ul> <!--menu--> <li class="nav-home"><a href="#content">Home</a></li> <li class="nav-portfolio"><a href="#lavori">Portfolio</a></li> <li class="nav-contact"><a href="#footer">Contact</a></li> </ul> </div> .nav-glob a:hover { color: red; } 

Then in jQuery, I used the click() function to set the css color property to red:

 $('.nav-home > a').click(function(){ $(".nav-home a").css("color", "red"); $(".nav-contact a").css("color", "white"); $(".nav-portfolio a").css("color", "white"); }); $('.nav-portfolio > a').click(function(){ $(".nav-home a").css("color", "white"); $(".nav-contact a").css("color", "white"); $(".nav-portfolio a").css("color", "red"); }); $('.nav-contact > a').click(function(){ $(".nav-home a").css("color", "white"); $(".nav-contact a").css("color", "red"); $(".nav-portfolio a").css("color", "white"); }); 

The problem is that it works fine the first time: after clicking a single link, the CSS hover property is ignored! It looks like hover disabled after clicking. Any help is much appreciated, thanks

+4
source share
3 answers

Try using CSS for differenct a :

 a.clicked { color: #f00; } a.hovered{ color: #f00 !important; } a.faded { color: #fff } $('#nav-glob ul li a').hover(function() { $(this).parent().siblings('li').find('a').removeClass('hovered'); $(this).addClass('hovered'); }, function() { $(this).parent().siblings('li').find('a').removeClass('hovered'); $(this).removeClass('hovered'); }).click(function(e) { e.preventDefault(); $('#nav-glob ul li a').removeClass('faded'); $(this).parent().siblings('li').find('a').addClass('faded'); $(this).addClass('clicked'); }); 

Demo

or just like @Blazemonger said

 a.faded { color: #fff } a.clicked { color: #f00; } a:hover{ color: #f00 !important; } $('#nav-glob ul li a').click(function(e) { e.preventDefault(); $('#nav-glob ul li a').removeClass('faded'); $(this).parent().siblings('li').find('a').addClass('faded'); $(this).addClass('clicked'); }); 

Demo

+3
source

Try :hover properties to !important and they should override the inline styles.

Alternatively, if you don't like using !important , you can use .toggleClass() to add and remove a specific class, and not to change CSS inline styles.

+2
source

Inline-styles overrides style styles. This is the expected behavior. Instead of returning the default color, remove the style attribute so that the stylish panel is back.

 $('#nav-glob a').click(function(){ var $this = $(this); $this.parent().siblings().children('a').removeAttr("style"); $this.css("color", "red"); }); 
0
source

Source: https://habr.com/ru/post/1413994/


All Articles