2

I know this is fairly easy in jQuery, but I want to do this in plain 'ol "will be around forever" javascript.

I have a dropdown select on my page. I choose one of 8 options. There is a default image showing on the page. When I select an option, the image changes to that pic. It all works fine.

But I want to make the image change a fade out, fade in switch over because I, like most of you, can't leave well alone. We have to keep fiddling.

The javascript that I have, which is triggered by an onchange="setPicture()" on the select dropdown is:

function setPicture(){
    var img = document.getElementById("mySelectTag");
    var value = img.options[img.selectedIndex].value;
    document.getElementById("myImageDiv").src = value;
}

This works fine. The value of the selected index is a string with the path for each image. I just want a fade out then fade in stuck in there somewhere. I have fiddled about a bit, calling another function before changing the src but no luck.

Can someone point me in the right direction?

Kelvin Aitken
  • 433
  • 6
  • 18
  • 1
    Possible duplicate of [CSS3 Transition - Fade out effect](https://stackoverflow.com/questions/15907079/css3-transition-fade-out-effect) – Randy Casburn Dec 14 '18 at 18:17
  • Native fades (indeed, jQuery fades, behind the scenes) rely on intervals and incrementing or decrementing an element's `opacity` property. It would be much easier to harness CSS3 transitions. – Mitya Dec 14 '18 at 18:17
  • So css transition opacity – epascarello Dec 14 '18 at 18:17

3 Answers3

3

The easier way would be to use css keyframes alone.

But from javascript there is the web animation api made for that.

Here is a quick modif from the example, to match your case.

function setPicture(){
 alice.animate(
  [
    { opacity: 1 },
    { opacity: .1},
    { opacity: 1 }
  ], {
    duration: 3000,
    iterations: Infinity
  }
 )
}
<button onclick="setPicture()">
  OPACITY ANIMATION
   </button>

<img id="alice" 
     src="https://mdn.mozillademos.org/files/13843/tumbling-alice_optimized.gif"
     >
  </img>
NVRM
  • 11,480
  • 1
  • 88
  • 87
0

How about setting the image default CSS with the opacity of 0 and with transition time then in JavaScript just add a class that will make the opacity set to 1

HTML: 
    <img class="img1" src="sampleimg.jpg">

CSS: 
    .img1 {
        opacity: 0;
        transition: all .3s;
    }
    .img1.show {
        opacity: 1;
    }

JS:
    function setPicture() {
        var img = document.querySelector('.img1');
        img.src = 'urlofnewimage';
        img.classList.add('show');
    }

Hope this helps.

boosted_duck
  • 478
  • 3
  • 15
0

Juste one function for all :

function fadeOutEffect(target) {
    var fadeTarget = document.getElementById(target);
    fadeTarget.style.opacity = 1;
    fadeTarget.style.transition = "opacity 2s";
    fadeTarget.style.opacity = 0;
    setTimeout(function(){
        fadeTarget.style.display = "none";
    }, 2000);;
}