Reputation:
Hello I am having a problem with .html function in jquery. event listener doesn't work anymore everytime i remove the script from the codes and paste it again. can you help me how to reactive script after it's re-paste in html.
Upvotes: 0
Views: 96
Reputation: 3928
Use this as an example:
$('a.button').live('click', function(){
//anchor tag clicked.
alert('Button has been clicked');
});
The .live()
:
Attach a handler to the event for all elements which match the current selector, now and in the future.
The .live() method is able to affect elements that have not yet been added to the DOM through the use of event delegation.
This means that you add and remove html from your page with .html()
and your events will still perform.
See the jQuery website for more information on .live()
A quick jsFiddle example.
Upvotes: 0
Reputation: 2527
I guess you are changing the inner html of some container with .html() function of jquery and the events you assigned are lost after the process. There are two approaches you can take:
If the content doesn't change use the .detach() function to remove and insert your elements back. The .detach() function preserves and event handlers attached to the elements you detach. However if you are inserting a different content then use .live() event to assign your events. The events that are assigned with .live() will be recreated when a element with the same selector is inserted into the dom.
Upvotes: 0
Reputation: 3175
You can set your events using .live()
method. Like:
$("#submit_button").live("click",function(e){
});
This way if you are adding/removing html from your page using .html()
method, the events will remain intact.
Hope that helps.
Upvotes: 1
Reputation: 1038730
You could use the .live()
method to register the event handler which will preserve it even if the corresponding DOM element is recreated. Example:
$(function() {
$('#someid').live('click', function() {
//
});
});
Upvotes: 0