I am trying to add a div and a span to an image on click and then remove it on the span click.
<div id="gallery" align="center">
<img src="http://www.frontpagejunky.com/wp-content/uploads/2011/05.jpg" class="img-view" width="150px" height="150px" />
</div>
The jquery:
$(document).ready(function(){
$('.img-view').click(function(){
var img=$(this).after('<span id="close">X Close</span>').wrap("<div id='pop-up' style='display:block'/>").clone();
$('#gallery').append(img);
});
$('#close').live("click",function(){
$('#pop-up').remove();
$('#close').remove();
});
});
</script>
The problem that I am having is that the span doesn’t get wrapped in the div, but only the image does, and the span is only appended after the image is wrapped.
The second problem is when I click the #close, the div and the button disappear, but when I click again on the .img-view , they don’t regenerate/reappear. why does that happen?
UPDATE
$(document).ready(function(){
$('.img-view').click(function(){
var img=$(this).clone();
img= img.after('<span class="close">X Close</span>');
img=img.wrap("<div class='pop-up' style='display:block'/>");
$('#gallery').append(img);
});
$('.close').live("click",function(){
$('.pop-up').remove();
$('.close').remove();
});
});
But now the pop up div doesn’t wrap the image element !?!
You cannot use wrap on element that are not in the dom. You can either create a new element that will be your wrapper and hook everything to that wrapper or first insert your img to the dom and then wrap it.
You should do either of these 2 options, first being best, before you add the span with the X.