I am trying to add fade in and out to my javascript code. Can someone please help me.
<script>
var text = ["Welcome", "Hi", "Sup dude"];
var counter = 0;
var elem = document.getElementById("changetext");
var inst = setInterval(change, 2500);
function change() {
elem.innerHTML = text[counter];
counter++;
if (counter >= text.length) {
counter = 0;
// clearInterval(inst); // uncomment this if you want to stop refreshing after one cycle
}
}
</script>
Sure. If you don’t mind using jQuery, this’ll do you:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Text fade in/out</title>
</head>
<body>
<div id="changetext">Welcome</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
var text = ["Welcome", "Hi", "Sup dude"];
var counter = 0;
var elem = $("#changetext");
var inst = setInterval(change, 2500);
function change() {
$(elem).fadeOut(
1000,
function(){
elem.innerHTML = text[counter];
$(elem).fadeIn();
}
);
counter++;
if (counter >= text.length) counter = 0;
}
</script>
</body>
</html>
jQuery comes with quite a nice fadeIn/fadeOut function, which (among other things) allows you to set a duration for the fade effect, as well as a callback to be run once the transition has taken place.