I am trying to implement a fade in/fade out feature that runs on a button click depending if some data was changed. I am using angular but the ngAnimate I could not get to work so I want to do it with pure js. What I currently have will flash the text for a second, then do nothing. This is inside my controller.
var warningText = document.getElementById('warningText');
warningText.style.display = 'inline'
$scope.warningText = "Warning: No Data was updated.";
var op = 0.0;
var fadeIn = setInterval(function() {
if (op >= 1) {
clearInterval(fadeIn);
fadeOut(op);
}
warningText.style.opacity = op;
op += op * 0.1;
}, 50);
var fadeOut = function(op) {
setInterval(function() {
if (op <= 0.1) {
clearInterval(fadeOut);
warningText.style.display = 'none';
}
warningText.style.opacity = op;
op -= op * 0.1;
}, 50);
}
Your calculation of op
is wrong as that will always be zero. Secondly the second function does not return the value from setInterval
, so you'll never be able to clear that interval.
Here is how you could do it with just one interval, where the sign of the increments to the opacity is reversed every time the boundary value is reached:
var warningText = document.getElementById('warningText');
function flickerMessage(msg) {
var op = 0.1;
var increment = +0.1;
warningText.textContent = msg;
warningText.style.opacity = 0;
warningText.style.display = 'inline';
var timer = setInterval(function() {
op += increment;
warningText.style.opacity = op;
if (op >= 1) increment = -increment;
if (op <= 0) {
warningText.style.display = 'none';
clearInterval(timer); // end
}
}, 50);
}
flickerMessage('Warning you');
<div id="warningText" style="display:none; opacity: 0">warning text</div>
<hr>