How do you fade in/fade out text via jQuery? That's the question a student brought to our December Dojo. The first solution we came up with used fixed text, but wouldn't it be nice if you could fade any text? Our revised solution, in the script below, takes an array as an argument and fades the text in and out that you send to the container.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<span id="container">Hello World</span>
<script>
// declare a function variable to write to the container
// the function takes two arguments: a container to hold the
// fade text and an array of values to write to the container
var f = function(cntnr, arrayVals) {
// assign local variables to point to the container and
// set the fade times
var c = $(cntnr),
fadeTime = 1500;
// use jQuery to iterate through the array. Kick off
// a generic function that acts on the container
$(arrayVals).each(function(idx, el) {
// fade out the existing text of the container
c.fadeOut(fadeTime, function() {
// write the new text to the invisible container
c.text(arrayVals[idx]);
// fade in the new text
}).fadeIn(fadeTime);
});
},
// create the array of messages
v = ["Message 1", "Message 2", "Message 3", "Message 4"];
// call the function, passing the container name and array
f("#container", v);
</script>
</body>
</html>