1

Here's what I think I want to do but I can't wrap my head around the right way to do it.

So I load a bunch of images into variables (think digital clock)...

var digit0 = "images/d0.png";
var digit1 = "images/d1.png";
var digit2 = "images/d2.png";
var digit3 = "images/d3.png";
var digit4 = "images/d4.png";
var digit5 = "images/d5.png";
var digit6 = "images/d6.png";
var digit7 = "images/d7.png";
var digit8 = "images/d8.png";
var digit9 = "images/d9.png";

Then in a loop I try to load those images into a div...

//SKIP A BUNCH OF TIMER CODE THAT WORKS AND GIVES ME "seconds".

var secondDigit = "digit"+(seconds.toString()).substr(1,1);
//Trying to make a string that refers to the matching variable above.

$("#d1").html('<img src="'+digit0+'" />');        //-- THIS ONE WORKS 
$("#d2").html('<img src="'+secondDigit+'" />');   //-- THIS ONE DOESN'T

Edit: So using this method, does it hit the server every time? If so, that's not what I want. I want to save the images once so I can use them over and over without hitting the server every time.

Thanks!

0

1 Answer 1

1

Your images will be cached by the browser, so no worries there.


Use an actual array instead of an array (:P) of variables:

var digits [
    "images/d0.png",
    "images/d1.png",
    "images/d2.png",
    "images/d3.png",
    "images/d4.png",
    "images/d5.png",
    "images/d6.png",
    "images/d7.png",
    "images/d8.png",
    "images/d9.png"
];

var secondDigit = seconds.toString().substr(1,1);

$("#d2").html('<img src="' + digits[secondDigit] + '" />');
6
  • That makes sense! But that will hit the server every time, correct? Is there a way to get the images one time and use them over and over?
    – Layne
    Jan 31, 2013 at 20:00
  • @Layne - Nope. The images will be cached by the browser. For better performance, you shouldn't be replacing those images, but updating their src. Jan 31, 2013 at 20:01
  • "updating their src" That's what I'd be doing with "$("#d2").html('<img src="' + digits[secondDigit] + '" />');" correct?
    – Layne
    Jan 31, 2013 at 20:08
  • @Layne - Nope. You're replacing those images. Here's a [non-functioning] fiddle with some sample code: jsfiddle.net/5KFW3 Jan 31, 2013 at 20:22
  • Is this comparable? $("#d2 img").attr("src", digits[firstDigit]); or does that also replace instead of update?
    – Layne
    Jan 31, 2013 at 20:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.