Search code examples
jqueryhtmlgallerylightboxphoto-gallery

Jquery code that copies one pictures source to another


I plan on eventually making a lightbox but I want to learn my way around javascript. My goal is that when you click one of the images, then it copies that images source and into the div with the id of "copiedTo"

I just cant figure out how my code is wrong. Here is the html:

<body>
    <div id="gallery">
        <ul>
            <li>
                <img src="1.jpg"/>
            </li>
            <li>
                <img src="2.jpg"/>
            </li>
            <li>
                <img src="1.jpg"/>
            </li>
            <li>
                <img src="2.jpg"/>
            </li>
            <li>
                <img src="1.jpg"/>
            </li>
            <li>
                <img src="2.jpg"/>
            </li>
        </ul>
    </div>

    <div id="copiedTo"><img src="#"/></div>
</body>

And my Javascript:

$(document).ready(function () {

            var image = $(this).attr('src');
            $('#gallery ul img').click(function() {
            $('#CopiedTo img').attr('src', image);
        });

        });

Thanks.


Solution

  • Please update your code to

    $(document).ready(function () {
         $('#gallery ul img').click(function() {
               var image = $(this).attr('src');
               $('#copiedTo img').attr('src', image);
         });
    });
    

    Also change your CopiedTo to copiedTo , check working jsfiddle here http://jsfiddle.net/5AGmp/