jQuery not executing the code for the new item with the new identifier

advertisements

I have an image, and when I click on it I want it to change to a different image and change its ID as well. Then when I click on this new image, it reverts back.

$(document).ready(function(){
    $("#name_edit").click(function(){
        $(this).attr("src", "img/tick.png");
        $(this).attr("id","name_confirm");
    });
    $("#name_confirm").click(function(){
        $(this).attr("src", "img/edit.png");
        $(this).attr("id","name_edit");
    });
});

I have successfully done the first step, going from #name_edit to #name_confirm. However, not the reverse.

How do I go about solving this?

My suspicion is that since I'm using (document).ready, jQuery is preparing itself for elements already on the page. However, the element with the ID name_confirm does not exist until the image is clicked on.

Thanks.


The element that you are working on is always the same...

$(document).ready(function(){

    // use just the first id value to find it in the DOM
    $("#name_edit").click(function(){
      var item = $(this);
      var id = item.attr('id');

      if(id === 'name_edit') {
        return item
          .attr("src", "img/tick.png")
          .attr("id","name_confirm")
        ;
      }

      return item
        .attr("src", "img/edit.png")
        .attr("id","name_edit")
      ;
    })
    ;
});