Efecto de letras aleatorias:un complemento de jQuery

En este breve tutorial, crearemos un complemento jQuery que mezclará el contenido de texto de cualquier elemento DOM, un efecto interesante que se puede usar en encabezados, logotipos y presentaciones de diapositivas.

El Código

El primer paso es escribir la columna vertebral de nuestro complemento jQuery. Colocaremos el código dentro de una función anónima autoejecutable y extenderemos $.fn .

activos/js/jquery.shuffleLetters.js

(function($){

    $.fn.shuffleLetters = function(prop){

        // Handling default arguments
        var options = $.extend({
            // Default arguments
        },prop)

        return this.each(function(){
            // The main plugin code goes here
        });
    };

    // A helper function

    function randomChar(type){
        // Generate and return a random character
    }

})(jQuery);

A continuación, centraremos nuestra atención en el randomChar() función auxiliar. Tomará un argumento de tipo (uno de "lowerLetter ", "letra superior " o "símbolo ") y devolver un carácter aleatorio.

function randomChar(type){
    var pool = "";

    if (type == "lowerLetter"){
        pool = "abcdefghijklmnopqrstuvwxyz0123456789";
    }
    else if (type == "upperLetter"){
        pool = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    }
    else if (type == "symbol"){
        pool = ",.?/\\(^)![]{}*&^%$#'\"";
    }

    var arr = pool.split('');
    return arr[Math.floor(Math.random()*arr.length)];
}

Podríamos haber usado una sola cadena de grupo para todos los tipos de caracteres, pero esto servirá para un mejor efecto.

¡Ahora escribamos el cuerpo del complemento!

$.fn.shuffleLetters = function(prop){

    var options = $.extend({
        "step"  : 8,    // How many times should the letters be changed
        "fps"   : 25,   // Frames Per Second
        "text"  : ""    // Use this text instead of the contents
    },prop)

    return this.each(function(){

        var el = $(this),
            str = "";

        if(options.text) {
            str = options.text.split('');
        }
        else {
            str = el.text().split('');
        }

        // The types array holds the type for each character;
        // Letters holds the positions of non-space characters;

        var types = [],
            letters = [];

        // Looping through all the chars of the string

        for(var i=0;i<str.length;i++){

            var ch = str[i];

            if(ch == " "){
                types[i] = "space";
                continue;
            }
            else if(/[a-z]/.test(ch)){
                types[i] = "lowerLetter";
            }
            else if(/[A-Z]/.test(ch)){
                types[i] = "upperLetter";
            }
            else {
                types[i] = "symbol";
            }

            letters.push(i);
        }

        el.html("");            

        // Self executing named function expression:

        (function shuffle(start){

            // This code is run options.fps times per second
            // and updates the contents of the page element

            var i,
                len = letters.length,
                strCopy = str.slice(0); // Fresh copy of the string

            if(start>len){
                return;
            }

            // All the work gets done here
            for(i=Math.max(start,0); i < len; i++){

                // The start argument and options.step limit
                // the characters we will be working on at once

                if( i < start+options.step){
                    // Generate a random character at this position
                    strCopy[letters[i]] = randomChar(types[letters[i]]);
                }
                else {
                    strCopy[letters[i]] = "";
                }
            }

            el.text(strCopy.join(""));

            setTimeout(function(){

                shuffle(start+1);

            },1000/options.fps);

        })(-options.step);

    });
};

El complemento tomará los contenidos del elemento DOM al que se invocó, o el texto propiedad del objeto pasado como argumento. Luego divide la cadena en caracteres y determina el tipo de cada uno. La función de reproducción aleatoria luego usa setTimeout() para llamarse a sí mismo y aleatorizar la cadena, actualizando el elemento DOM en cada paso.

Cuando vaya a la demostración, verá que puede escribir su propio texto y probarlo. Así es como lo hice:

activos/js/script.js

$(function(){

    // container is the DOM element;
    // userText is the textbox

    var container = $("#container")
        userText = $('#userText'); 

    // Shuffle the contents of container
    container.shuffleLetters();

    // Bind events
    userText.click(function () {

      userText.val("");

    }).bind('keypress',function(e){

        if(e.keyCode == 13){

            // The return key was pressed

            container.shuffleLetters({
                "text": userText.val()
            });

            userText.val("");
        }

    }).hide();

    // Leave a 4 second pause

    setTimeout(function(){

        // Shuffle the container with custom text
        container.shuffleLetters({
            "text": "Test it for yourself!"
        });

        userText.val("type anything and hit return..").fadeIn();

    },4000);

});

El fragmento anterior también muestra cómo puede usar el complemento y el texto personalizado. parámetro.

Terminado

Espero que encuentre útil este complemento y se divierta con él. Se publica bajo la licencia MIT.