mmm
mmm

Reputation: 2297

jQuery inserting and removing images from divs

Is there a way with jQuery to insert an image into a div on click, and remove it on click?

I am trying to make a light box with jquery, so on dom ready, it applies the thumbnail class to each image in the wrapper div, and then on click it toggles the full class. But that creates centering problems. So I'd like to have a transparent div that goes to .5 opacity and inserts the clicked image, then when you click again, does the opposite.

here's the code I have so far:

        $(document).ready
            $('img, div.wrapper').each( function() {
                var $img = $(this);
                $img.addClass('thumbnail');
                $img.click(function(){
                    $img.toggleClass('full');
                });
        });

link to the js fiddle: http://jsfiddle.net/reveries/TLJYN/

I just want to add a div that will be width and height 100% and 50% opaque which will have text-align set to center. This way when the image is injected into this div, it will automatically center. Then when clicked, the 50% opaque parent div will display:none and the image will be put back where it was before.

Upvotes: 1

Views: 1098

Answers (1)

Spokey
Spokey

Reputation: 10994

This will clone the clicked image into the div. You can change the css and the rest to your needs

$(document).ready(function(){
    $('img, div.wrapper').each( function() {
        var $img = $(this);
        $img.addClass('thumbnail');
        $img.click(function() {
            $img.clone().appendTo('#big');
        $('#big').fadeToggle('slow');
    });

    $('#big').click(function(){
        $('#big').fadeOut('slow').html('');
    });

});

I also changed some CSS. See Fiddle.

Upvotes: 1

Related Questions