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

3

2 Answers 2

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>

1
  • That's a lot of extra qork when he could just use better delegation as proposed by fermis
    – SpYk3HH
    Dec 5, 2014 at 21:17
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()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.