I need some help with my code. The task is to show an image by using a button. But the image has to show gradually with the CSS property "opacity".
The image should start at opacity 0 and should end at opacity 1.
Our teacher suggests us using "parsefloat" so the strings from CSS could be recognized by JS as numbers.
I do not really know why my code is not working. I would really appreciate it if you could show me where my mistake is.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Aufgabe 12.2</title>
<script>
var go = function() {
var opac = function(delay) {
var img = document.createElement("img");
img.src = "http://www.google.com/intl/en_com/images/logo_plain.png";
var level = 0;
var step = function(){
img.style.opacity = level;
if(level <= 1) {
level += .1;
setTimeout(step, delay);
}
}
step();
}
opac(100);
};
</script>
<body>
<input type = "button" onclick = "go();" value = "Click me"/>
</body>
</head>
</html>
Here is a working example:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Aufgabe 12.2</title>
<script>
var go = function () {
var opac = function (delay) {
var img = document.createElement('img');
img.src =
'http://www.google.com/intl/en_com/images/logo_plain.png';
document.body.appendChild(img);
var level = 0;
var step = function () {
img.style.opacity = level;
if (level <= 1) {
level += 0.1;
setTimeout(step, delay);
}
};
step();
};
opac(100);
};
</script>
<body>
<input type="button" onclick="go();" value="Click me" />
</body>
</head>
</html>
Here is a link with more information
You need to append the img node to the DOM:
const btn = document.querySelector("input")
btn.onclick = () => go(100)
var go = function(delay) {
var img = document.createElement("img");
img.src = "http://www.google.com/intl/en_com/images/logo_plain.png";
document.body.append(img)
var level = 0;
const step = function() {
img.style.opacity = level;
if (level <= 1) {
level += .1;
setTimeout(step, delay);
}
}
step();
}
<input type="button" value="Click me" />