tags:

views:

28

answers:

2

I have a list of images within a div tag with the id sIMG.

Example:

<div id="sIMG">
<img src="1.jpg" title=""/>
<img src="2.jpg" title=""/>
<img src="3.jpg" title=""/>
<img src="4.jpg" title=""/>
<img src="5.jpg" title=""/>
<img src="6.jpg" title=""/>
</div>

Now If I click on any image I need it to load into the sIMG div tag.

My code looks as follows, but only seems to load in the first image:

jQuery(document).ready(function(){

    jQuery('#sIMG img').click(function(){



        /* Get the sources */

        var currentSRC = jQuery('#sIMG img').attr('src');

        var altSRC = jQuery('#sIMG img').attr('title');

        alert(currentSRC)

        /*Fade, Callback, swap the alt and src, fade in */

        jQuery('#IMGHolder').fadeOut('fast',function(){

            jQuery('#IMGHolder').html('<img src='+currentSRC+' title='+altSRC+' />');

            jQuery('#IMGHolder').fadeIn('fast');

        });





    });

});

Am I doing something wrong here?

+2  A: 

Use

$(this) to access the current element inside the event handler.

jQuery(document).ready(function(){
        jQuery('#sIMG img').click(function(){
            /* Get the sources */
            var currentSRC = jQuery(this).attr('src');

            var altSRC = jQuery(this).attr('title');

            alert(currentSRC);

            /*Fade, Callback, swap the alt and src, fade in */

            jQuery('#IMGHolder').fadeOut('fast',function(){
                jQuery(this).html('<img src='+currentSRC+' title='+altSRC+' />').fadeIn("fast");                    
            });
        });

    });
rahul
+1  A: 

Am I doing something wrong here?

Probably. Inside a handler $(this) will give you a jQuery handle on the object that was clicked. You'll probably want jQuery(this).

What your current code does it goes out and looks for img elements regardless of the click event.

Your HTML is also malformed:

<div id="sIMG">
<img src="1.jpg" title=""/>
<img src="2.jpg" title="""/>
<img src="3.jpg" title="""/>
<img src="4.jpg" title="""/>
<img src="5.jpg" title="""/>
<img src="6.jpg" title=""/>
</div>

Should be

<div id="sIMG">
    <img src="1.jpg" title=""/>
    <img src="2.jpg" title=""/>
    <img src="3.jpg" title=""/>
    <img src="4.jpg" title=""/>
    <img src="5.jpg" title=""/>
    <img src="6.jpg" title=""/>
</div>

Ignore the indentation, it's the """ I took issue with.

Oli