Reputation: 203
I have a simple function to replace one image with others using JavaScript. And I have one line to fade in it when loading. But how can I add a fade in when the new image is displayed?
<script type="text/javascript">
function changeImage(a) {
document.getElementById("Image").src = a;
}
</script>
<div>
<img src="Mini-01.jpg" onclick="changeImage('Photo-01.jpg');">
<img src="Mini-02.jpg" onclick="changeImage('Photo-02.jpg');">
</div>
<div>
<img id="Image" src="Photo-01.jpg" onload="this.style.animation='fadein 2s'">
</div>
I tried using:
onchange="this.style.animation='fadein 2s'"
but it does not work.
I think it is too simple to use Jquery on this case.
Can you please helm me?
Upvotes: 0
Views: 529
Reputation: 9794
You can achieve the desired using css3 like this on changeImage() function.
@keyframes fadeIn { from { opacity:0; } to { opacity:1; } }
.container { top: 20%; left: 20%;}
.fade-in {
animation:fadeIn ease-in 1;
animation-duration:5s;
}
<script type="text/javascript">
function changeImage(a) {
var elm = document.getElementById("Image");
var clonedElm = elm.cloneNode(true);
elm.parentNode.replaceChild(clonedElm, elm);
document.getElementById("Image").src = a;
}
</script>
<div>
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/3c/Perkin_Warbeck.jpg/200px-Perkin_Warbeck.jpg" onclick="changeImage('https://upload.wikimedia.org/wikipedia/commons/thumb/3/3c/Perkin_Warbeck.jpg/200px-Perkin_Warbeck.jpg');">
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/9/97/Leonard_Cohen_2008.jpg/200px-Leonard_Cohen_2008.jpg" onclick="changeImage('https://upload.wikimedia.org/wikipedia/commons/thumb/9/97/Leonard_Cohen_2008.jpg/200px-Leonard_Cohen_2008.jpg');">
</div>
<div class="container">
<img id="Image" src="" class="fade-in">
</div>
Upvotes: 1
Reputation: 2647
You can write custom function for fadeIn like this:
function fadeIn(el) {
el.style.opacity = 0;
var tick = function() {
el.style.opacity = +el.style.opacity + 0.01;
if (+el.style.opacity < 1) {
(window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16)
}
};
tick();
}
//taken from http://stackoverflow.com/questions/23244338/pure-javascript-fade-in-function
function changeImage(a) {
var el = document.getElementById("Image");
el.src = a;
fadeIn(el)
}
where el = document.getElementById()
or something.
Here is https://jsfiddle.net/60x3bo8f/2/
Upvotes: 1