Reputation: 4452
I'm trying to create a fading effect using vanilla.js instead of jQuery. I'm using the following code to create the hide and show effect:
document.getElementById("pic-num-submit").onclick = function() {
fade();
};
var home = document.getElementById('home').style;
home.opacity = 1;
var agree = document.getElementById('agree').style;
agree.opacity = 0;
agree.display = "none";
function fade() {
if((home.opacity -= .1) < 0) {
home.display = "none";
show();
}
else {
setTimeout(fade, 40);
}
}
function show() {
if((agree.opacity += 0.2) < 1) {
agree.display = "";
}
else {
setTimeout(show, 40);
}
}
Everything is working with the fade function (in Firefox) But when I invoke the show function it only runs once, then it removes the display styling, and shows the div element at 0.2 opacity. I'm not sure what I'm doing wrong.
Here is a jsFiddle example of the problem I am having: http://jsfiddle.net/L54Aw/2/
Also it's broken in Chrome for some reason (The fade function never completes because of something to do with a js decimal subtracting problem)
Upvotes: 1
Views: 74
Reputation: 888
I can't comment on Pointy's solution, but here's what you could do with the fade function to avoid the bug that happens when you subtract low numbers:
function fade() {
home.opacity -= .05;
if(home.opacity - .05 < 0) {
home.display = "none";
show();
}
else {
setTimeout(fade, 20);
}
}
It isn't bulletproof, but it works by subtracting .05 instead of .1 and counter it by doubling the speed of the animation.
Upvotes: 1
Reputation: 413717
Your "show" function is not correct. You only set up the timer when the opacity is not less than one. Initially, it is, so the code only runs once.
You're also running into a weirdness in JavaScript that pertains to a significant difference between the +
and -
operators. Subtraction is always numeric, but not so addition!
Here's a working "show" function:
function show() {
agree.display = ""; // only need this the first time anyway
agree.opacity = +(agree.opacity) + 0.2;
if (agree.opacity <= 1)
setTimeout(show, 40);
}
That unary +
operator forces the "opacity" property to be interpreted as a number. Without that, it's a string! Thus adding 0.2
to the string "0.2" gives you "0.20.2", which is nonsense.
The decrementing you did for the other element worked OK because the subtraction operator coerces operands to numbers.
Upvotes: 4
Reputation: 13600
you probably want
(agree.opacity += 0.2) > 1
instead of
(agree.opacity += 0.2) < 1
Upvotes: 0