Reputation: 746
I am trying to colorize a string/word in HTML. I found a response here - but I am having trouble understanding how to convert to use the function more than once..
<div id="arch" style="font-size: 40px">First Word work fine</div>
<div id="arch" style="font-size: 40px">Second time - does not work</div>
var colours = ["#635636", "#FF00C0", "#990066", "#FF9966", "#996666", "#00FF00", "#CC9933"],
idx;
$(function() {
var div = $('#arch');
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);
}
});
How to create a function that I can call multiple times in a HTML?
Upvotes: 0
Views: 109
Reputation: 8872
You can only have one element with a particular id
. Replace your id
with class
(or add a particular class to elements) like follows
<div class="arch" style="font-size: 40px">First Word work fine</div>
<div class="arch" style="font-size: 40px">Second time - does not work</div>
javascript
//code has been update in response of observation made by adeneo, thanks adeneo
var colours = ["#635636", "#FF00C0", "#990066", "#FF9966", "#996666", "#00FF00", "#CC9933"],
idx;
$(function () {
$('.arch').each(function () {
var div = $(this),
chars = div.text().split(''),
span = '';
div.html('');
for (var i = 0; i < chars.length; i++) {
idx = Math.floor(Math.random() * colours.length);
span = span + $('<div>').append($('<span>' + chars[i] + '</span>').css('color', colours[idx])).html();
}
div.append(span);
});
});
I've added some code to avoid frequent update of DOM
Upvotes: 1
Reputation: 1055
As Ejay has mentioned, it doesn't work because you used ID's. You can only use an ID once on a page. What you want to use are classes.
Markup:
<div class="arch">You content</div>
Javascript:
var div = $('.arch');
I've also updated the JSFiddle: http://jsfiddle.net/8VDm4/1/
Upvotes: 0
Reputation: 34416
Change the id's on your div's to classes -
<div class="arch" style="font-size: 40px">First Word work fine</div>
<div class="arch" style="font-size: 40px">Second time - does not work</div>
And then change your selector in your jQuery -
var div = $('.arch');
Upvotes: 0