jacktheripper
jacktheripper

Reputation: 14219

jQuery append image to div animate

I think this question is best explained by giving you a jsFiddle. In that example, when the user clicks on of the gallery items, an image is appended to the div with id="showimage". What I cannot work out how to do is pass in the parameter of the image clicked, and display that image instead of an absolute one.

It should function as follows:

I think this would be best accomplished by 3 functions:

  1. Expand - append to showimage and animate from 0px to 100%
  2. Collapse - animate from 100% to 0px and remove from showimage
  3. Replace - call collapse on the image already in showimage, and call expand on the image clicked

Thanks in advance, any help would be much appreciated.

Upvotes: 0

Views: 2150

Answers (3)

jacktheripper
jacktheripper

Reputation: 14219

I managed to solve the problem, and you can see a live jsFiddle example here.

I kept the code really neat for this one - 3 separate functions, and 1 if statement to check if the showimage div had content.

The jQuery I used was as follows:

var add_image = function(clicked) {
    var image_create = '<img src="' + clicked + '">';
    $('#showimage').hide().append(image_create).slideDown(400);
};

var change_image = function(clicked) {
    $('#showimage img').slideUp(400, function() {
        $(this).remove();
        add_image(clicked);
    });
};

var remove_image = function() {
    $('#showimage img').slideUp(400, function() {
        $(this).remove();
    });
};

$('.gallery').click(function() {
    var len = $('#showimage').children().length;
    var clicked = $("img", this).attr('src');
    if (len === 0) {
        add_image(clicked);
    } else if (len === 1) {
        change_image(clicked);
    }
});

$('#showimage').click(function() {
    remove_image();
});​

Upvotes: 0

Anji
Anji

Reputation: 723

Without the animation in place. Your code should look something like this.

$(document).ready(function () {

    $('div.gallery').click(function (event) {

        var len = $('#showimage').find('img').length;
        var myimage = '<img src="http://s3images.coroflot.com/user_files/individual_files/302239_CauyLQoHZTkSJkkGnr3kVbFtw.jpg">';

        if (len === 0) {
            appendImage();

        }
       else {

            $('div#showimage').empty();
            appendImage();
      }

    });  

    function appendImage() {

       $('div#showimage').append(myimage);
       // your animation here 
    }  
});​

Upvotes: 1

Andreas Linden
Andreas Linden

Reputation: 12721

here I forked your fiddle and made it work as you want

http://jsfiddle.net/6vVUS/5/

Upvotes: 1

Related Questions