Fade In / Fade Out Script Via jQuery

Southwest Coder Dojo

Southwest Coder Dojo is a member of Coder Dojo International, an organization of free, volunteer-led coding clubs. We were founded to provide introductory coding experiences for youth and teens (ages 11-18). Our volunteer mentors are software developers and software industry professionals from the Twin Cities.

Register with Hennepin County Library to attend our Dojo events. Tickets are free, but seats are limited. No experience in programming required. Remember to bring your laptop!

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.

      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
      <span id="container">Hello World</span>

            // 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

                        // fade in the new text

            // 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);