Search code examples
javascripthtmlcsswebfade

Fading in a background image using javascript or css on hover


So far, i've been able to make it such that when the cursor hovers over the div a background image in the body appears. I need to add a fade in animation to this. Ive been looking for solutions here but havent been able to work around it. I don't have any experience in javascript.

enter code here
<script>


    changeBgImage = () => {
        document.body.style.backgroundImage = "url('../Images/Background/wraithback.jpg')";
        console.log("working")




    }
    ogBgImage = () => {
        document.body.style.backgroundImage = "url('../Images/Background/black.jpg')";
        console.log("working")
    }


</script>

<style>
    body {
        background-image: url('../Images/Background/black.jpg');
    }
</style>
<body>
<div class="gwraith"><a href="../Legends/wraith.html ">
                    <img src="../Images/Legends_pics/wraithchibi.png" width="130vw" class="wraith"
                        onmouseover="changeBgImage();" onmouseout="ogBgImage();">
                </a>
</body>

Solution

  • Add a transition rule to the body tag. The same can be done in css, without javascript.

    function changeBgImage() {
      document.body.style.backgroundImage = "url('https://s1.1zoom.ru/big0/284/Summer_Pond_Fence_Trees_496376.jpg')";
    }
    
    function ogBgImage() {
      document.body.style.backgroundImage = "url('https://pristor.ru/wp-content/uploads/2017/02/leto12.jpg')";
    }
    body {
      background-image: url('https://pristor.ru/wp-content/uploads/2017/02/leto12.jpg');
      background-repeat: no-repeat;
      background-size: cover;
      
      transition: all 0.7s linear;
      
    }
    <body>
      <div class="gwraith">
        <a href="../Legends/wraith.html">
        <img src="https://begin-english.ru/img/word/refresh.jpg" width="130vw" class="wraith"
                                onmouseover="changeBgImage();" onmouseout="ogBgImage();">
        </a>
      </div>
    </body>