2

I've implemented this code successfully in order toggle between img srcs using jquery, found from a previous solution.

$('img').on({
    'click': function() {
         var src = ($(this).attr('src') === 'img1_on.jpg')
            ? 'img2_on.jpg'
            : 'img1_on.jpg';
         $(this).attr('src', src);
    }
});

I was wondering if someone could help me to implement a fadeOut effect to transition between the img srcs, I've tried a handful of times and can't seem to wrap my head around jquery. Thank you very much for your help!

camusahn
  • 25
  • 4
  • Take a look at https://daneden.github.io/animate.css/ . You will find a lot more than fadeout, and is super easy to implement.! – Peyu Feb 25 '20 at 22:29

3 Answers3

2

Both .fadeOut() and .fadeIn() can take a second paramater to use as a function when their animation is complete - You can use this to update the src only once the image is hidden

You can then chain .fadeIn() as normal afterwards

$('img').on('click', function() {
  let src = ($(this).attr('src') === 'https://placekitten.com/125/?image=11')
    ? 'https://placekitten.com/125/?image=12'
    : 'https://placekitten.com/125/?image=11';
    
  $(this)
    .fadeOut(1500, () => $(this).attr('src', src))
    .fadeIn(1500);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<img src='https://placekitten.com/125/?image=11'/>

I've swapped around your code slightly for the demo / clarity

Shiny
  • 4,945
  • 3
  • 17
  • 33
0

If you want more of a transition between pictures rather than a full fade out and then full fade in, you can do this by using the background-image css property and css transitions:

$(function() {
  var img1 = 'url("https://www.fillmurray.com/200/300")';
  var img2 = 'url("https://www.fillmurray.com/g/200/300")'

  $("#theImage").on('click', function(){
    var src = ($(this).css('background-image') === img1)
        ? img2
        : img1;   
    $(this).css('background-image', src) 
  });
});
#theImage{
   display: inline-block;
    width: 200px;
    height: 300px;
    background-image: url("https://www.fillmurray.com/200/300");
    -webkit-transition: all 1200ms ease-in;
    -moz-transition: all 1200ms ease-in;
    -ms-transition: all 1200ms ease-in;
    -o-transition: all 1200ms ease-in;
    transition: all 1200ms ease-in;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 
<div id="theImage"></div>
ezanker
  • 24,628
  • 1
  • 20
  • 35
0

You can just use the hide() function before adding fadeIn() or fadeOut() effect. Thus, You will get your transition effect.

$('img').on({
     'click': function() {
        var src = ($(this).attr('src') === 'img1_on.jpg')
           ? 'img2_on.jpg'
           : 'img1_on.jpg';

     $(this).hide();
     $(this).attr("src",src).fadeIn("slow");
    }
 });
Meshu Deb Nath
  • 73
  • 1
  • 10