[RESOLVED]Pseudo Class being lost after jQuery applied

I have a standard unordered list containing anchor elements within <li> elements thus

<div id="navigation">
<ul>
	<li id="m1"><a id ='MM_Home' href="#">Home</a></li>
	<li id="m2"><a id ='MM_NatStand' href="#">National Standards</a></li>
	<li id="m3"><a id ='MM_Contacts' href="#">Manager Contacts</a></li>
</ul>
</div>

I have applied a pseudo class to the anchor elements in css so they highlight on hover

#navigation li a:hover { background: whitesmoke; }

All good.

There is no effective pseudo class for an onclick action so I have applied some jQuery to set the background colour of the clicked anchor element as well as

resetting the background colour of any previosly clicked anchor elements to the default.

$('#navigation li a').on('click',function() {
var $this = $(this);			
$this.css('background-color', '#00F4F4');	// set the background colour for the clicked item
$this.closest('li')	// find the closest li, which will be the containing li
	.siblings()	// find the siblings li items of the closest li
	.children('a')	// find their children anchor elements 
	.css( "background-color", "#5B9641" ) // reset their background colour
;

This works. However, the pseudo hover class applied thru the CSS no longer works.

I have a working method to re-apply the hover, but it is verbose and I don’t want to go there if not needed.

Thanks

Hi friend,

Madog

#navigation li a:hover { background: whitesmoke; }

You could use .hover() method in jquery instead of Pseudo-class.

$("#navigation li a").hover(function () {
                $(this).css('background-color', 'whitesmoke');
            }, function () {
                $(this).css('background-color', "");
            }); 

Hope it will be helpful to you.

Best Regards,

Fei Han

Thanks Fei Han,

I came up with this which works well. It could have been more eloquent if I could get toggleClass happening…..but it works!

$('#navigation li a').hover(
    function() {
    $(this).css('background-color','whitesmoke');
    },
    function() {
    if(typeof(clicked)  === "undefined")       // this is first time in before a menu item has been clicked
    {$(this).css('backgroundColor', '#5B9641');}
    else if (clicked.attr('id') == $(this).attr('id'))
    {
    // we hovered over the menu item's anchor element that has been clicked");
    $(this).css('backgroundColor', '#00F4F4');
    }
    else
    {
    $(this).css('backgroundColor', '#5B9641');
    };
    }
    );

Leave a Reply