Need help swapping images in a div

I’m guessing this is a pretty easy problem to fix, but I can’t find any code that will do what I need.

I have a group of images (all different sizes). Each image will have a corresponding text link. I need to be able to click on one of the text links and display the corresponding image in a separate div.

I found this example on Dynamic Drive, and it works, but the text links in this case are in a select box. If there is an easy way to just convert the select box links to plain text links, that would be ideal.


<form name="dynamicselector">
<table border="0" width="100%" cellspacing="0" cellpadding="0" height="178">
    <tr>
        <td width="35%" valign="top" align="left">
        <select name="dynamicselector2" size="4" onChange="generateimage(this.options[this.selectedIndex].value)">
            <option value="images/menus/mandarin-house-chef-special-01-sm.jpg" selected>DHTML Guide</option>
            <option value="images/menus/mandarin-house-chef-special-02-sm.jpg">DHTML QuickStart</option>
            <option value="images/menus/mandarin-house-chef-special-03-sm.jpg">HTML4</option>
            <option value="http://images.amazon.com/images/P/1861001746.01.TZZZZZZZ.jpg">IE5 DHTML</option>
        </select>
        </td>
        <td width="65%" valign="top" align="left">
            <ilayer id="dynamic1" width=100% height=178>
                <layer id="dynamic2" width=100% height=178>
                <div id="dynamic3"></div>
                </layer>
            </ilayer>
        </td>
    </tr>
</table>
</form>


<script>

//Dynamic Image selector Script- © Dynamic Drive (www.dynamicdrive.com)
//For full source code, installation instructions,
//100's more DHTML scripts, visit dynamicdrive.com

//enter image descriptions ("" for blank) this text appears under the image
var description=new Array()
description[0]="DHTML: The Definitive Guide"
description[1]="DHTML Visual QuickStart Guide"
description[2]="HTML 4 and DHTML"
description[3]="IE5 DHTML Reference"

var ie4=document.all
var ns6=document.getElementById
var tempobj=document.dynamicselector.dynamicselector2
if (ie4||ns6)
var contentobj=document.getElementById? document.getElementById("dynamic3"): document.all.dynamic3
function generateimage(which){
if (ie4||ns6){
contentobj.innerHTML='<center>Loading image...</center>'
contentobj.innerHTML='<center><img src="'+which+'"><br><br>'+description[tempobj.options.selectedIndex]+'</center>'
}
else if (document.layers){
document.dynamic1.document.dynamic2.document.write('<center><img src="'+which+'"><br><br>'+description[tempobj.options.selectedIndex]+'</center>')
document.dynamic1.document.dynamic2.document.close()
}
else
alert('You need NS 4+ or IE 4+ to view the images!')
}

function generatedefault(){
generateimage(tempobj.options[tempobj.options.selectedIndex].value)
}

if (ie4||ns6||document.layers){
if (tempobj.options.selectedIndex!=-1){
if (ns6)
generatedefault()
else
window.onload=generatedefault
}
}

</script>

Or if anyone has a better suggestion (I know the above code is really old), I’d be open to that as well.

Thanks in advance,

Steve

It references IE 4 and Netscape 4, that’s indeed a fair indication of old scripts :stuck_out_tongue:

It wouldn’t be too hard to write something like this from scratch.

In terms of markup you could have something like:


<ul class="gallery">
  <li><a href="/path/to/image.jpg" title="The longer description">Some link text </a></li>
  <li><a href="/path/to/image.jpg" title="The longer description">Some link text </a></li>
  <li><a href="/path/to/image.jpg" title="The longer description">Some link text </a></li>
</ul>

Then basic pseudocode for the JS would look like:


Find all gallery lists 

 Iterate through all gallery lists to find links

  apply (click) event handler to links

   prevent the default event from firing
   get the image path from the href and use it to generate a new image in the location you wish
   get the title attribute and add it below the image
   

I don’t have a clue what to do here. Can you be a little more specific? The HTML part of it is no problem. The JS is another story…

Something like this should help you get started.

The links for the images and link text are created dynamically according to the data in the picData array.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
        <title></title>
        <style type="text/css">
            #linksCont {
                list-style-type: none;
            }
            #img1{
                display: none;
            }
        </style>
        <script type="text/javascript">
            var picData = [
                ['pic1.jpg','show pic 1'],
                ['pic2.jpg','show pic 2'],
                ['pic3.jpg','show pic 3'],
                ['pic4.jpg','show pic 4']
            ];
            //preload the pics
            var picsObj = [];
            for(i=0; i < picData.length; i++){
                picsObj[i] = [];
                picsObj[i][0] = new Image();
                picsObj[i][0].src = picData[i][0];
                picsObj[i].lnkText = picData[i][1];
            }
            function showPic(num){
                img1Obj.style.display='inline';
                img1Obj.src = picsObj[num][0].src;
            }
            window.onload=function(){
                img1Obj = document.getElementById('img1');
                //create the links
                var ulObj = document.getElementById('linksCont');
                for(i=0; i < picsObj.length; i++){
                    var newLi = document.createElement('li');
                    var newA = document.createElement('a');
                    newA.num = i;
                    newA.appendChild(document.createTextNode(picsObj[i].lnkText));
                    newA.href='';
                    newA.onclick=function(){showPic(this.num);return false;}
                    newLi.appendChild(newA);
                    ulObj.appendChild(newLi);
                }
            }
        </script>
    </head>
    <body>
        <div>
            <img src="" id="img1" alt="" />
        </div>
        <ul id="linksCont"></ul>
    </body>
</html>

Thanks for the help, Max Height! I really appreciate it.

Is there any way to put a link behind the images?

Here is an alternative to Max’s post:

<ul id="linksCont"></ul>
<div id="picContainer"></div>
<script>
	var picData = ['447.jpg', '483.jpg', '494.jpg'],
          	linkCont = document.getElementById('linksCont'),
          	picCont = document.getElementById('picContainer'),
          	imgLinks = [],
          	i;
          	
	for( i = 0; i < picData.length; i++ ) {		
		linkCont.innerHTML += '<li><a href="#" class="imgLink" rel="' + picData[i] + '">Show Picture ' + (i + 1)  + '</a></li>';
	}
	
	// querySelectorAll compatibility: developer.mozilla.org/En/DOM/Document.querySelectorAll#Browser_compatibility
	imgLinks = document.querySelectorAll('.imgLink');
	for( i = 0; i < imgLinks.length; i++ ) {
		imgLinks[i].onclick = function() {
			picCont.innerHTML = '<img src="' + this.rel + '">';
		};
	} 			
</script>

If you want more information, can you do an object filled with the meta data needed like so:


var imgs = [
	{
		src: 'img1.png',
		alt: 'First Image',
		text: 'This is an image done on 1/1/2011.'
	},	
	{
		src: 'img2.png',
		alt: 'Second Image',
		text: 'This is an image done on 1/2/2011.'
	},
	{
		src: 'img3.png',
		alt: 'Third Image',
		text: 'This is an image done on 1/3/2011.'
	},								
];

for( var i = 0; i < imgs.length; i++ ) {
	var imgSrc = imgs[i].src,
		imgAlt = imgs[i].alt,
		imgTxt = imgs[i].text;
	console.log(imgTxt + '<img src="' + imgSrc + '" alt="' + imgAlt + '">')	
}

Yes, that can be done fairly easily. This is starting to sound a bit like some sort of homework exercise and so you should post at least your attempt and we can then help you get it working.

But essentially, all you need to do is:

  1. wrap the <img> in an <a> in the html

  2. add the url you want each clicked image to navigate to in the image’s row in picData

  3. add 1 line of code in showPic(num) to set the href of the <img>'s <a> to the url for that image

1 - I think I got that part right
2 - this one too
3 - Purely a guess on my part. I have no clue what to do here.

Here’s what I’ve got so far:


        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
            "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
        <html xmlns="http://www.w3.org/1999/xhtml">
            <head>
                <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
                <title></title>
                <style type="text/css">
                    #linksCont {
                        list-style-type: none;
                    }
                    #img1{
                        display: none;
                    }
                </style>
                <script type="text/javascript">
                    var picData = [
                        ['http://www.nova.edu/hpd/otm/pics/4fun/11.jpg','show pic 1','http://www.thenightowl.com'],
                        ['http://www.nova.edu/hpd/otm/pics/4fun/12.jpg','show pic 2','http://www.thenightowl.com'],
                        ['http://www.nova.edu/hpd/otm/pics/4fun/13.jpg','show pic 3','http://www.thenightowl.com'],
                        ['http://www.nova.edu/hpd/otm/pics/4fun/14.jpg','show pic 4','http://www.thenightowl.com']
                    ];
                    //preload the pics
                    var picsObj = [];
                    for(i=0; i < picData.length; i++){
                        picsObj[i] = [];
                        picsObj[i][0] = new Image();
                        picsObj[i][0].src = picData[i][0];
                        picsObj[i].lnkText = picData[i][1];
                    }
                    function showPic(num){
                        img1Obj.style.display='inline';
                        img1Obj.src = picsObj[num][0].src;
						img1Obj.href = picsObj[num][2].href;
                    }
                    window.onload=function(){
                        img1Obj = document.getElementById('img1');
                        //create the links
                        var ulObj = document.getElementById('linksCont');
                        for(i=0; i < picsObj.length; i++){
                            var newLi = document.createElement('li');
                            var newA = document.createElement('a');
                            newA.num = i;
                            newA.appendChild(document.createTextNode(picsObj[i].lnkText));
                            newA.href='';
                            newA.onclick=function(){showPic(this.num);return false;}
                            newLi.appendChild(newA);
                            ulObj.appendChild(newLi);
                        }
                    }
                </script>
            </head>
            <body>
                <div>
                    <a href=""><img src="" id="img1" alt="" /></a>
                </div>
                <ul id="linksCont"></ul>
            </body>
        </html>

Am I close?

You need to give the <a> an id and then use getElementById() (google it for more info if required) to change the link’s href to the url in picData for the current image.

Use the error console in your browser to view any error messages when you open your web page.