/    Sign up×
Community /Pin to ProfileBookmark

create dynamic vars

Ok a simple problem (I hope)… I have a few images that preload. When i call the script fo the image to load i want to be able to determine the height of the image being loaded. The problem arises when I want the image to load randomnly.

[CODE]
Image1= new Image(478,400)
Image1.src = “http://www.mysite.com/image1.jpg”

Image2 = new Image(368,400)
Image2.src = “http://www.mysite.com/image2.jpg”
var maxpics = 2;
var picheight
function picload() {

if (randnum > maxpics) {
randnum = 1;
}
var newimg = [“Image”+randnum].src; <—-//I know this is wrong, this is where I am stuck…
picheight= newimg.height;
}
[/CODE]

i want picheight to return the height of the random img source. I don’t know how to combine the variables so it will work or not come out undefined. Thanks in advance for any help.

to post a comment
JavaScript

5 Comments(s)

Copy linkTweet thisAlerts:
@GSharpMay 07.2008 — You want to use eval to turn the string into an actual variable. So it should look something like:

var newimg = eval("Image"+randnum);
Copy linkTweet thisAlerts:
@javaddikauthorMay 07.2008 — Thanks for the quick reply. Works great, I knew it was something simple I was forgetting.
Copy linkTweet thisAlerts:
@Declan1991May 07.2008 — Or window["Image"+randnum].src;

I prefer that method.
Copy linkTweet thisAlerts:
@toicontienMay 07.2008 — You should be using an array here.
var imgs = [];
function loadImage(src, width, height) {
var i = imgs.push( document.createElement("img") ) - 1;
imgs[i].src = src;
imgs[i].width = width;
imgs[i].height = height;
return i;
}

loadImage("http://www.mysite.com/image1.jpg", 478, 400);
loadImage("http://www.mysite.com/image2.jpg", 368, 400);
Copy linkTweet thisAlerts:
@javaddikauthorMay 07.2008 — Now that you mention it an array probably would work better in my situation being I have up to 10 images. I will revise using the sample. Thanks for all the help.

Chalk up [B]two[/B] new things learned today ?
×

Success!

Help @javaddik spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...