views:

222

answers:

2

I currently have a jQuery function that replaces an image when clicked. For instance:

  <script type="text/javascript">

  $('#test').click(function(event) {
  event.preventDefault();
  img = $('<img id="myImage" class="photo" src="newImage.jpg>');
  $("#myImage").remove().append(img);
  });

   $('#myImage').click(function(event) {
  event.preventDefault();
  alert("You clicked the image");
  </script>

And my HTML is as follows:

<a id="test">Click Here to Change Picture</a>

 <div id="profilepic" class="fb6a">
      <img id="myImage" class="photo" src="oldImage.jpg>
 </div>

So, I noticed that, I "change" the picture and replace it with a new "image", I lose the event handler associated with the new image, even if it has the same "ID."

Any way to avoid this?

Thanks!

+1  A: 

Can't quite remember how the event bubbling goes in HTML DOM, but can't you attach the click handler to the surrounding div? That one certainly doesn't change, and it may avoid what sounds to me like some kind of leak.

flq
A: 

Try the live event.

Peter Di Cecco
That works perfect for me, thanks!
Dodinas