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>
You might find it easier to control the opacity using CSS. Its less work for the browser and only requires minimal javascript to toggle the class.
var img = document.getElementById("dog"),
btn = document.getElementById("button");
btn.addEventListener("click", function( event ) {
img.className = (img.className==="in")?"out":"in";
}, false);
#dog {
opacity: 0;
-webkit-transition: opacity 2s ease;
-moz-transition: opacity 2s ease;
-ms-transition: opacity 2s ease;
-o-transition: opacity 2s ease;
transition: opacity 2s ease;
}
#dog.in {
opacity: 1;
}
<button id="button">Lets Rock</button><br />
<img id="dog" src="http://lorempixel.com/500/500/cats/" class="off" draggable="true" ondragstart="drag(event)" width="500" height="500">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With