Search code examples
javascriptjqueryhoverif-statementrollover-effect

IF ELSE Hover statement only works on second hover


I have a menu, that when you roll over the image the image changes, unless the image has an active class attached. My problem is that the image only changes on the SECOND ROLL OVER not the FIRST. Any ideas why this is.

$("#contact").hover(function () {
    if ($("#contact").is(".active")) {
        $("#contact img").attr("src","Images/Menu/contact_hover.png" )
    }
    else {
        $("#contact").hover(function () {
                $("#contact img").attr("src","Images/Menu/contact_hover.png" )
            },
            function() {
            $("#contact img").attr("src","Images/Menu/contact.png" )
         });
    }
});

Solution

  • You shouldn't be doing this with jQuery, there really is no need. Please read up on CSS Image sprites and use the css hover selector like this:

    #contact {
        background: url(/url/of/img) no-repeat;
    }
    
    #contact:hover { 
        background-position: ; // Change to desired image
    }
    

    Do this to change the background position of the image sprite you use, if you're lazy you could change the image altogther instead of bothering with sprites. You will find this method much lighter page size, as well as compatibility.