1

I have an element with some id, I changed its ID and when I click on that element (with new ID now), it still calls the function with previous ID

$('#1st').click(function(){
    $('#1st').attr('id','2nd');
    alert("id changed to 2nd");
});
$('#2nd').click(function(){
    alert("clicked on second");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="javascript:;" id="1st">Click</a>

Example is here

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
baig772
  • 3,404
  • 11
  • 48
  • 93

2 Answers2

3

Because you add the event before the element exists. It does not find an element. Either attach the event when you change the id or you need to use event delegation.

    $('#1st').on("click.one", function(e) {
      $('#1st').attr('id', '2nd');
      alert("id changed to 2nd");
      e.stopPropagation();
      $(this).off("click.one");
    });
    $(document).on("click", '#2nd', function() {
      alert("clicked on second");
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#" id="1st">Click</a>
epascarello
  • 204,599
  • 20
  • 195
  • 236
1

Try doing it this way jsFiddle

    $(document).on('click', '#2nd', function(){
  alert("clicked on second");
 })
 .on('click', '#1st', function(e) {
  $('#1st').attr('id','2nd');
  alert("id changed to 2nd");
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#" id="1st">Click</a>

Also see this post on using Jquery's .on() versus .click()

Community
  • 1
  • 1
Fermis
  • 181
  • 6