Search code examples
javascripthtmlcssimagefade

Fade Out an Image when click on button, change image url and then fade in. How to do it?


I am creating a website and I need some help with an issue. I will upload a picture for you to understand it better.

I have a big image in the middle, and below it there are some words that act like links(). I need this to happen: 1. The big image appears as the website loads. 2. When I click on a button (the words acting as links), I want the big image to fade out, then change the image src (so a different image will be displayed in the big image container) and then this different image will appear fading in.

It's something like this:

I've already tried to get this by using some jQuery, but I don't get it to work. I thought it would be something like this, but it's not working, as the image src changes, then the image appears, and after that the image fades out, leaving an empty space instead of the image:

$('.button3').on({
    'click': function(){
        $("#change-image").fadeOut("slow");
        $('#change-image').attr('src','img/project3.jpg');
        $("#change-image").fadeIn("slow");
    }
});

$('.button4').on({
    'click': function(){
        $("#change-image").fadeOut("slow");
        $('#change-image').attr('src','img/project4.jpg');
        $("#change-image").fadeIn("slow");
    }
});

etc.

Can anybody help me solving this? I know how to fade out, how to change image src, and how to fade in, but I can't do all together as I would like.

Thank you very much!!


Solution

  • fadeOut takes a second parameter, a function. You can then do what you need to do after the first image is faded out.

    $('.button3').on({
        'click': function(){
            $("#change-image").fadeOut("slow", function() {
                $('#change-image').attr('src', 'https://images.freeimages.com/images/large-previews/d2f/tulips-1400882.jpg');
                $("#change-image").fadeIn("slow");
            });             
        }
    });
    img {
      height : 150px;
      width : 200px;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <img id="change-image" src="https://images.freeimages.com/images/large-previews/c98/ferns-3-1405636.jpg"/>
    <br/><button class="button3">Click</button>