I am new to JavaScript. I am really intrigued to figure out an easy technique for changing the opacity of an image that is laying on top of another image to reveal that bottom image gradually. I want to do this by fading out. In other words subtracting from the style.opacity property gradually after each second passes with time.
I came up with the following but it doesn't seem to work for me.
The current state of my code changes the opacity suddenly goes from 1 to the negatives (-0.1, -0.2, -0.3, etc). Which basically does a transition from the top image immediately to revealing the bottom one.
I want to gradually go from opacity of 1 to (0.9, 0.8, 0.7, etc) as each second passes.
I want to accomplish this in pure JavaScript. I found something similar in CSS but I don't want to use that approach.
I assume that (var currentOp = document.getElementById('guitar2').style.opacity;)
treats the currentOp variable as a string. Because of this I tried a combination of parsing to float, making the subtraction and changing back to string, setting the opacity gradually over time to not avail.
<!DOCTYPE>
<html>
<head>
<style>
#guitar1
{
position: relative;
top: 0;
left: 0;
}
#guitar2
{
position: absolute;
top: 0px;
left: 0px;
opacity: 1;
}
</style>
</head>
<body onload="runTime()">
<script>
var timer;
function reduceOpacity()
{
var op = document.getElementById('guitar2');
var currentOp = document.getElementById('guitar2').style.opacity;
//currentOp = (parseFloat(currentOp) - 0.1).toString();
currentOp -= 0.1;
op.style.opacity = currentOp;
}
function runTime()
{
timer = setInterval(reduceOpacity, 1000);
}
</script>
<h4 id="header">Gibson Les Paul</h4>
<div style="position: relative; left: 0; top: 0;">
<img src="gibson1.png" id="guitar1" width="500" />
<img src="gibson2.png" id="guitar2" width="500" />
</div>
<button type="button" onclick='document.getElementById("header").innerHTML = "yea"'>Click Me!</button>
</body>
</html>