Pergunta

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" )
         });
    }
});
Foi útil?

Solução

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.

Outras dicas

It's because you aren't making the second call to hover until the else-block runs the first time. Set all of you event handlers up in $(document).ready, and you should be good to go.

you should simplify your code - try this

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

Working example at: http://jsfiddle.net/HNGMT/

**The example uses two divs to demonstrate the difference between one with the class of active and one without. The HTML of cours is solely for demonstration purposes as well. And the jQuery selector for the contact class would be modified to reflect the id selector.

HTML:

<div class="contact"><img src="/contact.png" alt="contact inactive" /></div>
<div class="contact active"><img src="/contact.png" alt="contact active" /></div>

JavaScript:

$(".contact").hover(function () {
    $(this).find("img").attr({src:"contact_hover.png", alt:"contact hover"});
}, function(){
    var ele = $(this);
    if(!ele.hasClass("active")){
        ele.find("img").attr({ src:"contact.png", alt:"contact inactive"});
    }
});
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top