Search code examples
jquerycssbackground-imagetransitionfade

Fade one background image for another on hover of link using jquery or css transition properties


Title might be a bit confusing.

I have .main-container div holding my entire page content.

On link hover on #cheffing I need to change .main-container's background image from one image to another and fade between the two images.

Problem is, during the fade, I want my content inside .main-container to still be visible, only have the background image be effected, not the whole container.

I'm not even sure how to tackle this. Should I use just jQuery? CSS? classToggle()? fadeOut()? I'm not sure...

I'm using jQuery. Sorry if this doesn't make sense. If you need more I'll be around.

Code Pen

https://codepen.io/JDSWebService/pen/NjmrRv

HTML

<div class=".main-container">
  Other Misc Page Content
  <a href="#" id="cheffing">Cheffing</a>
  Other Misc Page Content
</div>

CSS

.main-container {
  height: 100vh;
  background: url("../imgs/background.jpg");
  background-size: cover;
  background-position: 0 0;
  background-repeat: no-repeat;
  transition: background 1s ease-out;
}

Solution

  • You can't animate a background.

    Here is an simple example.

    So, positionning an image element within the element you want to have a background as absolute with a lower z-index will bring it behind the rest of the content.

    Then the use of .hover() can switch between two images URL.


    EDIT
    Here is a second example using 2 images instead of 2 URL on 1 image (to avoid the the white in between).

    HTML:

    <div class=".main-container">
      <img id="background-1" src="firstImage.jpg">
      <img id="background-2" src="secondImage.jpg">
      content...
    

    CSS:

    .main-container {
      height: 100vh;
      background-size: cover;
      background-position: 0 0;
      background-repeat: no-repeat;
      transition: background 1s ease-out;
    }
    #background-1,#background-2{
      position:absolute;
      z-index:-1;
      width:100%;
      height:500px;
    }
    #background-2{
      display:none;
    }
    

    jQuery:

    var fadeOptions = {
      duration:600,
      easing:"linear"
    };
    
    $("#cheffing").hover(function(){
      $("#background-1").fadeOut(fadeOptions);
      $("#background-2").fadeIn(fadeOptions);
    },
    function(){
      $("#background-2").fadeOut(fadeOptions);
      $("#background-1").fadeIn(fadeOptions);
    });