Search code examples
jquerycssbackground-imagefade

Adding a fade in and out transition to background image on hover


I have a simple navigation system in a sidebar on a page that you can see here.

As you can see when you hover over one of the links in the sidebar the background image changes as I have set a different background URL for hover in the CSS. I am looking for a simple way of adding a transition effect, so that the hover background image fades in and out. I have tried a couple of jQuery methods without success. I am wondering if there is a way of adding a fade transition using jQuery or some other method to the background URL image, or whether I have to use a different method to get a transition effect.

Thanks,

Nick


Solution

  • It's difficult to say what you're trying to do without some clarification, or some example code, but are you looking for something like this?

    $("#someElement").hover(function() {
        $(this).stop().fadeOut("1000", function() {
           $(this).attr("src", "anotherImage.png").fadeIn(1000);
        }); 
    }, function() {
        $(this).stop().fadeOut("1000", function() {
           $(this).attr("src", "firstImage.png").fadeIn(1000);
        }); 
    });
    

    In this example, #someElement refers to an img element. The src attribute is changed on hover, with a fade effect.

    Edit - having re-read your question, I think you want to change the background-image CSS property, rather than the src of an img element. If that's the case, have a look at this example. All that has really changed is replacing the jQuery attr function with css.