Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Jquery. Change element id

Status
Not open for further replies.

zura

Technical User
Sep 20, 2011
23
GE
Helo,
I try to change element id and then do something with it.
This script changes id, but click not works with it, I dont understand why.

Thanks for help.

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

zura said:
I dont understand why.
The [tt]click[/tt] event handler was already added to all elements with [tt]id[/tt] new when the script was executed.
The [tt]id[/tt] of elements with [tt]id[/tt] some will be changed to [tt]id[/tt] new somewhere in the future when the user will generate a [tt]mouseover[/tt] event.

So you will need to add event handlers again after you set the [tt]id[/tt] which you wish to use for element selection.

However I would rethink all this. No idea what is your goal and what are the restrictions, but for now this sounds as poor design.


Feherke.
feherke.github.io
 
I agree with feher. dynamically changing the id sounds like very poor design

in order to bring nodes dynamically within an event handler's purview there are two approaches:

1. after changing something rebind the events.
2. bind the event handler to the document and then filter.

e.g.

Code:
function doBind(){
 $('.someClass').on('click', function(e){
  //do something
 });
}
$('#some').hover(
    function(e){
        $(this).addClass('someClass');
        doBind();
    }, function(e){
        $(this).removeClass('someClass');
        doBind();
    }
);

Code:
$(document).on('click', ".someClass", function(e){
  //do something
});
$('#some').hover{
    $('#some').hover(
    function(e){
        $(this).addClass('someClass');
    }, function(e){
        $(this).removeClass('someClass');
    }
);
 
Thanks for help and advice.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top