JQuery each letter in a div element, random color from an array on hover

I am trying to get every letter in a div element in order to jump to a random color from an array of colors. Then reset when the mouse leaves the div.

Here is what I have so far. I think I'm pretty close, apart from the fact that this actually doesn't work. It was created from several different fragments on this site.

$(document).ready(function() {

    // COLOURS ARRAY
    var colours = Array("#ddd", "#333", "#999", "#bbb"), idx;

    $("DIV#header").hover(function(){

        $( $(this).text().split('')).each(function(index, character) {
            idx = Math.floor(Math.random() * colours.length);
            $(this).css("color", colours[idx]);
        });

    }, function() {
        $(this).css("color","#ddd");
    });

});

It does not cause JS errors. The second guidance function seems to work, but not the first. Any help would be greatly appreciated!

+5
source share
4 answers

A string is not an element, and you cannot add a CSS property to it. You can put your letters in span elements and then style them, try the following:

$(document).ready(function() {

    // COLOURS ARRAY
    var colours = Array("#ddd", "#333", "#999", "#bbb"), idx;

    $('DIV#header').hover(function(){

        $('span', this).each(function(index, character) {
            idx = Math.floor(Math.random() * colours.length);
            $(this).css("color", colours[idx]);
        });

    }, function() {
        $('span',this).css("color","#ddd");
    });

}); 

http://jsfiddle.net/BC5jt/

+3

, <span> span.

#header {color: #ddd}​
<div id="header">Some text here</div>
$(document).ready(function() {

    // COLOURS ARRAY
    var colours = Array("#ddd", "#333", "#999", "#bbb"), idx;

    $("#header").hover(function(){
        var header = $(this); 
        var characters = header.text().split('');
        header.empty();  
        var content = '';
        for(var i = 0; i < characters.length; i++) {
            idx = Math.floor(Math.random() * colours.length);
            content += '<span style="color:'+colours[idx]+'">' + characters[i] + '</span>'; 
        }
        header.append(content);
    }, function() {
        $(this).find('span').contents().unwrap();
    });

});

http://jsfiddle.net/vVNRF/

+8

, , , , <span> . , :

$(document).ready(function() {

    // COLOURS ARRAY
    var colours = ["#ddd", "#333", "#999", "#bbb"], 
        idx;

    $("DIV#header").hover(function(){
        var div = $(this); 
        var chars = div.text().split('');
        div.html('');     
        for(var i=0; i<chars.length; i++) {
            idx = Math.floor(Math.random() * colours.length);
            var span = $('<span>' + chars[i] + '</span>').css("color", colours[idx])
            div.append(span);
        }

    }, function() {
        $(this).find('span').css("color","#ddd");
    });

});​

http://jsfiddle.net/Mv4pw/

+4

As others have pointed out, you can only stylize something that is an element, so you need to wrap each letter in its own element. Here is an example of how to do this. It also works recursively, so this will work with text that contains other elements, such as <b>, <a>etc. Other examples below assume that the div will only have text and other HTML tags inside.

var colours = Array("#ddd", "#333", "#999", "#bbb");

$('#header').hover(function(){
    wrapLetters(this);
    $('.random-color', this).css('color', function(){
        var idx = Math.floor(Math.random() * colours.length);
        return colours[idx];
    });
}, function(){
    $('.random-color', this).css('color', '#ddd');
});

// Wrap every letter in a <span> with .random-color class.
function wrapLetters(el){
    if ($(el).hasClass('random-color')) return;

    // Go through children, need to make it an array because we modify
    // childNodes inside the loop and things get confused by that.
    $.each($.makeArray(el.childNodes), function(i, node){
        // Recursively wrap things that aren't text.
        if (node.nodeType !== Node.TEXT_NODE) return wrapLetters(node);

        // Create new spans for every letter.
        $.each(node.data, function(j, letter){
            var span = $('<span class="random-color">').text(letter);
            node.parentElement.insertBefore(span[0], node);
        });

        // Remove old non-wrapped text.
        node.parentElement.removeChild(node);
    });
}

Fiddle: http://jsfiddle.net/aWE9U/2/

+4
source

All Articles