loxol loxol - 3 months ago 10
CSS Question

Fading between images in a list

I have some javascript set up so that when I

hover
an image, it changes to a different image. The only problem is, that it's instant. How would I add a transition to this to make it smooth, to fade between the images?

<div class="social">
<ul class="sociallinks">
<li>
<a href="https://www.linkedin.com/in/lee-jordan">
<img class="linkedinIcon" src="assets/images/linkedin.png" />
</a>
</li>
<li>
<a href="https://github.com/loxol">
<img class="githubIcon" src="assets/images/github.png" />
</a>
</li>
</ul>
</div>


$(document).ready(function() {
$(".linkedinIcon").hover(function() {
$(this).attr("src", "assets/images/linkedinhover.png");
}, function() {
$(this).attr("src", "assets/images/linkedin.png");
});
});

Answer

You can do it on different ways, but you can't fade the same image when replacing the src. You could use two img tags, or even place the hover image as background of the img tag, and fade out the image on hover using css transitions. Here is one example:

$(function() {
    $(".linkedinIcon").hover(function() {
        $(this).css("opacity", 0);
    }, function() {
        $(this).css("opacity", 1);
    });
});
ul.sociallinks {
  list-style: none;
}
ul.sociallinks a {
  width: 300px;
  height: 200px;
  display: block;
}
ul.sociallinks img {
  -webkit-transition: opacity 1s;
  -moz-transition: opacity 1s;
  transition: opacity 1s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="social">
  <ul class="sociallinks">
    <li>
      <a href="#" style="background-image: url('http://dummyimage.com/300x200/2e97c7/2e97c7&text=2');">
        <img class="linkedinIcon" src="http://dummyimage.com/300x200/c72cc7/c72cc7&text=1" />
      </a>
    </li>
  </ul>
</div>

Even possible without JS at all, css only:

ul.sociallinks {
  list-style: none;
}
ul.sociallinks a {
  width: 300px;
  height: 200px;
  display: block;
}
ul.sociallinks img {
  -webkit-transition: opacity 1s;
  -moz-transition: opacity 1s;
  transition: opacity 1s;
}
ul.sociallinks img:hover {
  opacity: 0;
}
<div class="social">
  <ul class="sociallinks">
    <li>
      <a href="#" style="background-image: url('http://dummyimage.com/300x200/2e97c7/2e97c7&text=2');">
        <img class="linkedinIcon" src="http://dummyimage.com/300x200/c72cc7/c72cc7&text=1" />
      </a>
    </li>
  </ul>
</div>