views:

32

answers:

4

Hi all, bit of a jquery rookie here trying to get something to work. Basically I have a div with a class "nav" and inside that div is a nav list. I want to change the background-image of "nav" when hovering over an item in the navlist, so I made this unsuccesful effort:

enter code here

$(function(){

        $("li#hover-first").mouseover(function(){
        $("div.nav").removeClass("nav").addClass("navbg");
        .mouseout(function(){$("div.nav").removeClass("navbg").addClass("nav");
});

So the idea is, once the first li item is hovered over, the div with classname "nav" has it's class removed and has "navbg" added (which has the alternate background image). Obviously this isn't working, so any help would be greatly appreciated...thanks.

A: 

try:

$("div.nav").css("background", "backgroundImage.jpg");

just replace "backgroundImage.jpg" to whatever you want the background css value to be set to, the same as if it were defined in the css stylesheet.

derek
A: 

You should use jQuery's hover method:

$("li#hover-first").hover(
    function() { $("div.nav").removeClass("nav").addClass("navbg"); },
    function() { $("div.nav").removeClass("navbg").addClass("nav"); }
);
SLaks
A: 

You can use the .hover() and .toggleClass() methods to make what you want pretty concise, like this:

$("li#hover-first").hover(function() {
  $("div.nav, div.navbg").toggleClass("nav navbg");
});

The main change is that you need the div.navbg selector as well because when you're hovering out it would currently be <div class="navbg">, so div.nav no longer matches it. The .toggleClass() with a space separation just toggles both of the classes, effectively swapping them in this case.

Nick Craver
A: 

Both SLaks and Nick are correct in pointing out that you can use the hover method instead of mouseover and mouseout. However, this is more for convenience and shouldn't make a big difference. JQuery's documentation even says...

Calling $(selector).hover(handlerIn, handlerOut) is shorthand for: $(selector).mouseenter(handlerIn).mouseleave(handlerOut);

The toggleClass method is a similar convenience.

I see two real problems with your existing code. The first one is pointed out and corrected by Nick and that is his modified selector.

The main change is that you need the div.navbg selector as well because when you're hovering out it would currently be < div class="navbg">, so div.nav no longer matches it.

The second problem I see is that you don't end your functions. This isn't mentioned by Nick or SLaks but is addressed because their answers are written differently.

If there was some reason you didn't want to use hover and toggleClass your corrected code would look like this:

$(function(){    
    $("li#hover-first").mouseover(function(){
        $("div.nav").removeClass("nav").addClass("navbg");
    }).mouseout(function(){
        $("div.navbg").removeClass("navbg").addClass("nav");
    });
});
drs9222