user3192948
user3192948

Reputation: 261

JQuery Click() not working after element ID change

I try to change element id and then do something with it. This script changes id, but click does not work. Some friends provided the following solution, but I would like to understand why.

Thanks for help.

$('#some').hover(
   function(){
       $(this).attr('id', 'new');
   }
);
$('#new').click(
   function(){
       $(this).fadeTo('slow' , 0.2);
   }
); 

Solution:

$('#new').on('click',
function(){
   $(this).fadeTo('slow' , 0.2);
}
);

But why can't I use 'click' directly?

Update:

Thank you all for the answer. Here's a follow up: I used the 'on' method to initiate the click event. Can I then include the same id in the function itself for it to fade?

Code:

       $('#new').live('click',
        function(){
       $('#new').fadeTo('slow' , 0.2);
       }
       );

I tried on my end but it failed to start the event. Any workaround suggestion is appreciated.

Upvotes: 0

Views: 1943

Answers (2)

AlvaroAV
AlvaroAV

Reputation: 10563

Try this code:

$('#some').hover( 
    function(){ $(this).attr('id', 'new'); 
    $('#new').click( function(){ 
          $(this).fadeTo('slow' , 0.2); 
    })  
}); 

Your problem is when you define the second function, there is no element called $('#new') and the function cannot be binded, so if you define the second function inside the first, you avoid this.

I tried this code, and works perfect for me

1st)Change the id of #some to #new when mouse is over #some element

2nd)Fade #new when clicked #new element

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82241

You are changing the DOM property dynamically. And events are attached to DOM, not to DOM property like class,id,name-value, etc. To make it work,Event delegation is the solution:

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

$(document).on('click','#new',function(){
   $(this).fadeTo('slow' , 0.2);
}); 

Upvotes: 4

Related Questions