Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.clone() an element, then add dynamic styling to it

Let's say I have an image, cat.jpg, and when clicked I want to clone it.

$('img.cat').on("click", function() {
  $(this).clone().appendTo('#container');
});

Upon duplication, however, I want the new cat.jpg to appear as half the size of the original. And I want this to continue happening each time a new cat.jpg is clicked.

Any ideas on how to go about accomplishing this? Is it even possible to inject new styling/classes/parameters via .clone()?

like image 721
daveycroqet Avatar asked Feb 14 '23 05:02

daveycroqet


2 Answers

It sounds like the following is what you're after:

// If all images are within #container, use $("#container") instead:
$(document).on("click", "img.cat", function () {
    var original = $(this);
    original.clone().css({
        width: original.width() / 2,
        height: original.height() / 2
    }).appendTo("#container");
});

Fiddle: http://jsfiddle.net/G6XTz/

Of course, you may have wanted the newly added image to be half the size of the last cat image, rather than the cat image clicked:

Fiddle2: http://jsfiddle.net/G6XTz/1/

Caveat:

The width and height can only divide so far; eventually you'll run into some problems. Better check the result of division first, and make a decision to do something else when it makes sense.

like image 122
Sampson Avatar answered Feb 17 '23 03:02

Sampson


Just setting the width to half seems to be enough with an img element, the height gets set automatically in proportion to the width:

$('#container').on('click','img.cat', function() {
    $(this).clone()
           .appendTo('#container')
           .width(function(i,v) { return v/2;});
});

Demo: http://jsfiddle.net/Mr2x8/

But if you find you need to set the width and the height here's one way to do it:

$('#container').on('click','img.cat', function() {
    var $this = $(this);
    $this.clone()
         .appendTo('#container')
         .width($this.width()/2)
         .height($this.height()/2);
});

Demo: http://jsfiddle.net/Mr2x8/1/

like image 26
nnnnnn Avatar answered Feb 17 '23 01:02

nnnnnn