Hi all,

I have a new website that has a portfolio page. Currently, the code is such:

<input type="image" src="_images/01.png" id="01" alt=""
onclick="document.getElementById('outputDiv').innerHTML = 
'<section class=gallery><img src=_images/img01.jpg>' +
'<p>Image name - by Photographer</p></section>';" />

This seems extremely cumbersome and is impractical for a site that could have many images on several pages since the above code was for just one image. I would like to have a function that looked at the thumbnail image id and took that id number and placed it in an outputDiv text string as such:

 function ShowImg()   
{
  var img;

  img = document.getElementById('').value;
  document.getElementById('outputDiv').innerHTML = 
   '<img src=_images/img' + img + '.jpg>';
 }


 IN BODY: 

<input type="image" src="_images/01.png" id="01" alt="" onclick="ShowImg()" />

So, how do I get past the fact that each id is different? A friend suggested using an if statement, but that doesn't make sense to me. I thought about an array, but I would rather not have to go and update the array everytime I add/substract images from the gallery. I would just like to be able to look at the id value and pop it into a text string.

Thoughts?

Recommended Answers

All 2 Replies

I still need assistance with this one.

Do you want the replacement to be in the same 'div'? If so, you could 'hard-coded' the function; otherwise, pass in the div ID you want it to be replaced to (below).

// Be careful, this function does NOT verify incoming arguments.
// If element of divId does not exist, it will stop all other script.
// If imgSrc does not lead to a loaded image or no image, it will not display an image.
function ShowImg(divId, imgSrc) {
  document.getElementById(divId).innerHTML = "<img src=\""+imgSrc+"\">";
}

//IN BODY:
<input type="image" src="_images/01.png" id="01" alt="" onclick="ShowImg('aDivId', '_images/01.png')" />
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.