PDA

View Full Version : Get img src by getElementById and applying it throughout


mhito
05-22-2007, 04:08 AM
hi guys,

My first post yes. Thanks for all the nice posts and threads in this forum - great stuff.

Now, here's my question:

First off, the url : http://catfish.businesscatalyst.com/bcimg.htm

When you get there an alert of the div/img name in question appears. It splits and grabs the 'name' from images/name.jpg.

If you look at the source, this value is set to var = bb.

My problem now is to apply this throughout this little script(s). What I want to do is take this var 'bb', and concatenate a '_back' to it so its something like 'name_back.jpg'. You see something similar in the script source ( toggleDisplay() function).

What this does is swap the 'view back'/'view front' image of a swimsuit, and i want it to grab 'preloaded' image (by a CMS) hence the var bb, then be able to pull the name_back.jpg image when you swap it in the script.

For some reason when I replace toggleDisplay('look_in_source_for_name_here') with 'bb', it doesn't work. I'm pretty terrible with JS.

I'd much appreciate the help - thanks for taking the time to read this.

Cheers

Mike

_Aerospace_Eng_
05-22-2007, 08:01 AM
It doesn't work because the scope of the variables is local. You need to make them global. Change this
function findImgPath(){
var bgImg = document.getElementById('product_normal').getElementsByTagName('img')[0].src;

var a = bgImg.split("/");
var a_length = a.length-1;
var aa = a[a_length];

var b = aa.split(".");
var b_length = b.length;
var bb = b[0];

//alert(bgImg); //full bgImg string
//alert(a); //elements in array of bgImg string
//alert(aa); //full image name
alert(bb); //image name without filetype
}
to this

var aa, bb;
function findImgPath(){
var bgImg = document.getElementById('product_normal').getElementsByTagName('img')[0].src;

var a = bgImg.split("/");
var a_length = a.length-1;
aa = a[a_length];

var b = aa.split(".");
var b_length = b.length;
bb = b[0];

//alert(bgImg); //full bgImg string
//alert(a); //elements in array of bgImg string
//alert(aa); //full image name
alert(bb); //image name without filetype
}
Now you should be able to pass bb to the toggleDisplayfunction. Note since you are passing it a variable you don't use quotes. It would look like this
toggleDisplay(bb)

glenngv
05-22-2007, 09:43 PM
Or you can make the findImgPath function return the image name.
function findImgPath(){
var bgImg = document.getElementById('product_normal').getElementsByTagName('img')[0].src;

var a = bgImg.split("/");
var a_length = a.length-1;
var aa = a[a_length];

var b = aa.split(".");
var b_length = b.length;
var bb = b[0];

//alert(bgImg); //full bgImg string
//alert(a); //elements in array of bgImg string
//alert(aa); //full image name
alert(bb); //image name without filetype

return bb;
}<body onload="toggleDisplay(findImgPath());">