Reputation: 2701
i am trying to fix this problem but i am unable to solve it..
I am getting text from a database, a marquee text that scrolls,
the point is, i want to change the color of text randomly just
after each comma(,) separation...
i am able to change the text on page load randomly but the whole
text is changed. I want to change text after the omma..
eg. Hello, I am, Nick,
Now Hello Should be displayed in different color, and so on...
Here is my code, but it does all the text random color
var colours = Array("yellow", "white", "green", "orange"), indexNo;
$('#header').each(function (index, character) {
indexNo = Math.floor(Math.random() * colours.length);
//alert(idx);
$('#header').css("color", colours[indexNo]);
});
}, function () {
$('#header', this).css("color", "#ddd");
});
Upvotes: 1
Views: 1264
Reputation: 191789
$("#header").each
is not necessary since there is only one of those. You can just use the string .split
method.
$("#header").html(function (_, html) {
return html.split(',').reduce(function (prev, cur) {
return prev + "<span style='color: " +
colours[Math.floor(Math.random() * colours.length)] + ";'>"
+ cur + "</span>";
}, '');
});
http://jsbin.com/abikin/1/edit
EDIT: if the commas don't have to go inside of spans you can use this instead:
return html.split(',').map(function (elem) {
return "<span" ... + elem + "</span>"
}).join(',');
http://jsbin.com/abikin/3/edit
Upvotes: 3
Reputation: 11817
I just reworked Explosions a little because .reduce is for IE9 or above (I think). I am sure he can do a more elegant version than the following... but worth a shot. Though this gives you all text are random, not sure that is what you want. If not, sorry.
var colours = Array("yellow", "black", "green", "orange","red","purple");
var newHtml = [];
$("#header").html(function (_, html) {
$.each(html.split(','),function (_,obj) {
newHtml.push("<span style='color: " + colours[Math.floor(Math.random() * colours.length)] + ";'>" + obj + "</span>");
});
return newHtml.join(',');
});
Upvotes: 1