Reputation: 925
I am trying to replace text with images (each character would have its own image), with the ability to update the text on the page and the corresponding images.
For example, I want to be able to output: "SCORE: 1,034" with images, and be able to update the score as the user progresses. As the score gets higher and higher, there would need to be more commas, there would be extra columns of digits, etc. 0 -> 103 -> 1,034 -> 102,304 etc.
I am thinking I would probably have have a single image for "SCORE", and then an image for each number and a comma, but I'm having trouble writing a function that replaces each character with it's corresponding image.
Is there a simple way to do this with JavaScript/jQuery and/or CSS?
Thank you!
Upvotes: 0
Views: 188
Reputation: 10403
you want to have an array to hold the url for each digit image url:
var digitImages = [
'http://example.com/0.jpg',
'http://example.com/2.jpg',
'http://example.com/3.jpg',
'http://example.com/4.jpg',
'http://example.com/5.jpg',
'http://example.com/6.jpg',
'http://example.com/7.jpg',
'http://example.com/8.jpg',
'http://example.com/9.jpg'
];
then a simple routing that looks up each digit inside the digitImages
.
var imgs = [];
var text = 130.toString();
for(var i = 0; i < text.length; i++)
{
var index = parseInt(text[i], 0);
imgs.push(new Image(digitImages[index]));
}
now the content of imgs
array should be all the image elements for number 130
which can be appended to a div or other container elements.
Upvotes: 1
Reputation: 6334
The easiest way would be to have a function that takes the number and adds the commas and then you can replace the characters with images.
Sample function
function C(a,b){return(a+"").replace(/\d+/,function(a){return a.replace(/\d(?=(?:\d{3})+(?!\d))/g,"$&"+(b||','))})}
C(1001)//returns 1,001
Upvotes: 1