jQuery each letter in div element, random colour from array on hover

╄→尐↘猪︶ㄣ 提交于 2019-11-29 04:43:57

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 this:

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

You can only add styles to elements, wrap each character in a <span> and style the 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/

As others have pointed out, you can only style something that is an element, so you need to wrap each letter in it's own element. Here is an example way to do this. It works recursively too, so this will work with text that contains other elements, like <b>, <a>, and such. The other examples below assume that the div will have only text and no 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/

Well, it's exactly what Musa said, you can't apply styles to text nodes, you need a <span> element around each character. Here is some example code that adds the spans dynamically:

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!