Log in

View Full Version : var image pathways



maddoccanis
02-16-2014, 05:18 PM
I have a lot of images with long paths in the <img> statements. I wanted to put the pathway (which is usually the same) into a a var to clean up my code. The obvious approach (to me ) didn't work. How do i do it?

traq
02-16-2014, 10:55 PM
The obvious approach (to me ) didn't work.

And what is "the obvious approach"? You need to describe what you did, and what actually happened (vs. what you expected to happen). Showing us the code you're working with is always helpful as well.

Also, this is not a question about graphics: what programming language are you using? My guess would be javascript, but let me know and I'll move your thread to the appropriate forum.

If it's javascript, you assign a variable with the assignment operator ( = ). The var keyword and the variable name go on the left, and the value goes on the right, like so:
var nameOfMyVar = "value of my var";

Your question is unclear.
Please provide more information, and be as specific as possible.
What do you want to accomplish? What have you already tried? What problems did you encounter?
Please be sure that you have included all relevant code and/or a link to the page in question.
You might also consider making a reduced test case (http://css-tricks.com/reduced-test-cases/) using an online tool like jsfiddle (http://jsfiddle.net)

Is this related to your other thread (http://www.dynamicdrive.com/forums/showthread.php?76403-Why-doesn-t-this-work)? If you're still working on the same problem, there's no need to start a new thread.

We still need more information, but here's an example of a pattern you might follow:
// put all of your image paths into an array
var paths = [
"path/to/img-1.png",
"path/to/img-2.png",
// etc.
];

// choose where you will insert the images on your html page
var parentElement = document.getElementById( "id-of-element-which-new-imgs-should-be-inserted-inside" );

// loop through each image path; for each path:
for( i=0; i<paths.length; i++ ){

// create a new image element
var img = document.createElement( "img" );

// set the new image's src attribute to the desired path
img.src = "http://example.com/" + paths[i];

// insert the new image into the html page.
parentElement.appendChild( img );
}

Beverleyh
02-17-2014, 07:28 AM
You might be better using PHP in case visitors have JavaScript turned off. Since PHP is server-side, it would also avoid any unnecessary flashes while JavaScript takes a moment to write the image paths and loads them in.

Same type of setup;


<?php $path = '/path/to/img/folder/';?>

<img src="<?php echo $path;?>pic1.jpg" />
<img src="<?php echo $path;?>pic2.jog" />