Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Wee Beastie

macrumors regular
Original poster
Aug 20, 2007
195
0
In the snow with Rosebud
Hello,

I ran across a very simple Javascript image swap solution that works nearly perfectly for my needs and is easy to implement. If possible I would like to edit this script or add another function to it that would pull text (perhaps from the title attribute) and display it as a caption underneath.

Here is the javascript:

function swapImage(elem)
{
if (!document.getElementById) return false;
var bigPic = elem.getAttribute('href');
document.getElementById('mainpic').setAttribute('src', bigPic);
}


The <a> tag needs to have this as an attribute: onclick="swapImage(this);return false;"

The image that is to be replaced should have an id that matches the script. In this case id="mainpic"

Can anyone help me pull text out of the html and display it along with the image that is being swapped? Calling me a javascript noob would be an understatement.

If you need more info from me, just let me know. Thank you!
 
Here's an updated function,
PHP:
function swapImage(elem)
{
  if (!document.getElementById) return false;
  document.getElementById('mainpic').src = elem.href;
  document.getElementById('mainpic').alt = elem.title; // not really needed, but doesn't hurt
  document.getElementById('main_pic_caption').innerHTML = elem.title;
}
Here's some sample HTML
HTML:
<img id="mainpic" src="default.jpg" alt="" />
<p id="main_pic_caption"></p>
<p><a href="image.jpg"
  onclick="swapImage(this); return false;"
  title="Some title"><img src="image_thumb.jpg" alt="" /></a>
</p>
I replaced the getAttribute and setAttribute functions. IE has some issues with these functions some times, so the updated way is more likely to work with more browsers. You'll probably want to add some CSS to the caption and the like, but that was out of the scope of the question. I didn't test the code, but I'm fairly confident in it.
 
I replaced the getAttribute and setAttribute functions. IE has some issues with these functions some times, so the updated way is more likely to work with more browsers. You'll probably want to add some CSS to the caption and the like, but that was out of the scope of the question. I didn't test the code, but I'm fairly confident in it.

No worries. Thank you very much for your help. I'll test it out tonight and let you know how it goes. Thanks again!
 
angelwatt,

The script works perfectly. I am really pleased to have that issue ironed out. Thanks again!

I seldom post to the forum, but I read it nearly every day and I have picked up a ton of great info that you and others have generously shared.

Thank you to you all.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.