Adam Katz
Adam Katz

Reputation: 6962

Use jQuery to add a picture from one div to another

I want to use jQuery to add an image that is on a div to another div, but when I do it the image disappears from the original div. I would like the image to be copied and not moved. Here is the current code.

$( ".rectangle" ).click(function() {
    $('.bigRectangle').css('display','block');
    $(".notBig").css('opacity',0.2);
    var x = $(this).find('img');
    $('.bigRectangle').append(x);
});

Upvotes: 3

Views: 52

Answers (2)

Mr Alexander
Mr Alexander

Reputation: 62

All you would need to do is perform this:

var x = $(this).find('img').clone();

I would recommend you check out the function clone "https://api.jquery.com/clone/"

In your code you are essentially moving the image, when you assign the image in the variable "x" it holds the dom element in that variable. It is a reference. Matter of fact you are holding all images in the document.

Hope this helps, please let me know.

Mr Alexander

Upvotes: 2

Alexander O'Mara
Alexander O'Mara

Reputation: 60527

This is because a DOM node can only have one parent. Appending it to another element will move it to being a child of the other element. Use the .clone method to clone the img element before appending it.

$('.bigRectangle').append(x.clone());

Upvotes: 5

Related Questions