Mary
Mary

Reputation: 365

How to append an image in div using jQuery?

I have a list of small images while clicking on each of them they should show up in the div(the idea is to see them bigger)

I have used append function jQuery but it does not work

Here is the jQuery code:

$(function() {
    $('.selectable a img').click(function() {
    var img=$(this).attr('src');    
    alert(img);// this is what i get  data/100.jpg but it does not show up in div
    ('#div1').append('img');
  });

});

part of CSS Code:

 <ul> 
    <?php foreach ($cakeTypeService->getByTypeAndSubtype('stage', 'ROSE') as $cake) { ?>
     <li class="selectable" id="cakeType-<?= $cake->id ?>">
       <a href="?cakeType=<?php echo ($cake->id); ?>" title="Selecteer">
       <?php if ($cake == $order->cakeType){?><span class="checked"></span><?php } ?>
       <img src="data/<? echo $cake->id ?>.jpg" alt="" width="50" height="50" /></a>                                 
      </li>
     <?php } ?>
  </ul>

Upvotes: 1

Views: 22528

Answers (4)

chhameed
chhameed

Reputation: 4446

you can see this live demo right here http://jsfiddle.net/chhameed/nWqcv/

Hope it helps .

Upvotes: 1

Barış Velioğlu
Barış Velioğlu

Reputation: 5817

Have you tried ?

$(function() {
    $('a img').click(function() {
    $img=$(this).attr('src');    

    $('#div1').append("<img src="+$img+" />")

  });

});

Upvotes: 5

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76880

you are missing a $ (here ('#div1')) and doing some weird things with what you append (actually you are trying to append a collecttion of all images on the page. (selected with $('img');

try this:

$(function() { 
$('.selectable a img').click(function() { 
var img=$(this);//img is the image clicked
//append the img to the div
$('#div1').append(img); });

});

EDIT added comments

Upvotes: 0

Gavin Osborn
Gavin Osborn

Reputation: 2603

I know your question specifically asked for how to manually achieve this but there are existing plugins out there that would do the bulk of this work for you:

A great example here.

Another example here.

You could use this plugin or at least use it for inspiration to write your own.

Upvotes: 1

Related Questions