Mr.freelance
Mr.freelance

Reputation: 65

Smooth CSS background image transition

I have this little js script: it works but the problem is when I hover buttons quickly the smooth transition effect doesn't work and it makes it very ugly when the img change suddenly.

thanks for helping.

var buttons = document.querySelectorAll("#section2_list li");
  var div_img = document.getElementById('div_img');
    
  buttons[0].addEventListener("mouseover", function() {
    div_img.style.backgroundImage = "url(https://picsum.photos/id/237/200/100)";          
  });
    
  buttons[1].addEventListener("mouseover", function() {
    div_img.style.backgroundImage = "url(https://picsum.photos/id/238/200/100)";          
  });
#div_img {
  width:  200px;
  height: 100px;
  transition: all 0.9s ease ;
 }
<ul id="section2_list">
  <li>one</li>
  <li>two</li>
</ul>

<div id="div_img">
</div>

Upvotes: 3

Views: 8793

Answers (1)

Alexander Presber
Alexander Presber

Reputation: 6625

Directly transitioning the background-image property is not possible as background-image is not an animatable property.

But you can stack two images and transition the top images' opacity to achieve the desired effect:

var buttons     = document.querySelectorAll("#section2_list li");
var img_default = document.getElementById('img_default');
    
buttons[0].addEventListener("mouseover", function() {
  img_default.style.opacity = 0;
});
    
buttons[1].addEventListener("mouseover", function() {
  img_default.style.opacity = 1;
});
#div_img {
  width:  200px;
  height: 100px;
}

#div_img img {
  position: absolute;
}

 #img_default {
   transition: all 0.9s ease ;
 }
<ul id="section2_list">
  <li>one</li>
  <li>two</li>
</ul>

<div id="div_img">
  <img src="https://picsum.photos/id/237/200/100" />
  <img id="img_default" src="https://picsum.photos/id/238/200/100" />
</div>

Upvotes: 2

Related Questions