views:

234

answers:

2

Hello, I have a menu and jquery-code, which makes its background-image different when hover.

       $('#menu a').hover(function() {
            $(this).css( 'background', 'url(images/slider_bg_hover.png) repeat-x' );                     
       },function(){
            $(this).css( 'background', 'url(images/slider_bg.png) repeat-x' );
       });

It works fine, but now I want to highlight clicked menu:

$('#menu a').click(function() {
   $(this).css( 'background', 'url(images/slider_bg_hover.png) repeat-x' );
});

It works fine too, but after clicking I move my mouse-pointer from menu-area and hover-action calls! So that part of menu is unhiglighted!

What can u advice me?

+2  A: 

Rather than setting individual css attributes, consider using classes instead.

Your example would require three css classes (two of which have the same definition)

.menu{
    background: url(images/slider_bg.png) repeat-x;
}

.hoverMenu, .selectedMenu{
    background: url(images/slider_bg_hover.png) repeat-x;
}


$('#menu a').hover(function() {
        $(this).addClass('menu');                     
   },function(){
        $(this).addClass( 'hoverMenu' );
   });

$('#menu a').click(function() {
   $('#menu a').removeClass( 'selectedMenu' );
   $(this).addClass('selectedMenu');
});

When an element has two classes that conflict with each other, I think that the one which comes last, in the CSS definitions, is the one that takes effect. It's a bit late at night for me to check this, but you can swap the classes around to see which way works best..

belugabob
+1 - I think that's what my confused mind was striving towards.
karim79
Sorry for long reply, I wasn't able to test this code. Thanks, it works fine.
Ockonal
+1  A: 

You could also consider putting an !important after the css rule for selected, so it would ovverride the hover rule. (Using the above solution).

CodeJoust
Okay, thank you for advice.
Ockonal