0
votes

I'm new to jQuery, so I think this will be trivial for many. I'm making a navigation bar with sub menus that appear when the main menu are hovered on. I want to change the background image of the main menu and, in the same time, show the sub menu. Here is my code:

$('#nav-list li.products').hover(
        function() { 
            $('#nav-list li.products ul').addClass("hover");
            $(this).css("background-image","url(img/products-hover.png)"); 

        },
        function() {
            $('ul', this).removeClass("hover");
            $(this).css("background-image","url(img/products.png)");
        }
    );

This code only shows the submenu, but doesnt update the style for the main menu. How can I achive this in jQuery? Thanks!

1
It would be helpful if you could post your nav bar markup as well. - Matt Ball

1 Answers

0
votes
$(this).css("background-image","url(img/products-hover.png)"); 

The above code will add background-image: url(img/products-hover.png to the current web page's DOM.
So I suppose the image img/products-hover.png may be relative to the css file but may not be relative to the current URL.

Try with a URL that is relative to the root path like /img/products-hover.png or I would prefer a absolute path in this scenario like http://www.example.com/img/products-hover.png

Example

$('#nav-list li.products').hover(
        function() { 
            $('#nav-list li.products ul').addClass("hover");
            $(this).css("background-image","url(http://www.example.com/img/products-hover.png)"); 

        },
        function() {
            $('ul', this).removeClass("hover");
            $(this).css("background-image","url(http://www.example.com/img/products.png)");
        }
    );