I am a new-newbie in JavaScript and I am trying to write a code that fades-in a picture in commands that I am familiar with. I've seen several examples here but they didn't work. This is what I tried to do:
function myFunction() {
for (i = 1; i < 20; i++) {
setTimeout(function() {
o = 1 - 1 / i
}, 200); //this should increase the opacity
document.getElementById("dog").style.opacity = o
}
}
img {
opacity: 0;
filter: alpha(opacity=40);
}
<center>
<img id="dog" src="dog.jpg" draggable="true" ondragstart="drag(event)" width="500" height="500">
</center>
<button onclick="myFunction()">Lets Rock</button>
when I ran it, it doesn't do fade in. it starts with blank screen (as it should), but than instead of fading in after I click the button, it just pops out (without fading in) after a few clicks.
thank you very much for help given
Ariel
Try this : http://jsfiddle.net/kishoresahas/4wg8zcsg/
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();
}
function myFunction() {
var el = document.getElementById("dog");
console.log(el);
fadeIn(el);
}
img {
opacity: 0;
filter: alpha(opacity=40);
}
<button onclick="myFunction()">Lets Rock</button>
<center>
<img id="dog" src="https://i.sstatic.net/NHlV8.jpg" draggable="true" ondragstart="drag(event)" width="500" height="500">
</center>