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.
-
In particular, "doesn't work anymore" isn't very descriptive. Describe exactly what you expect to happen and what actually happens, including any error messages. When asking about code, include a minimal sample. For webpages, include a link to a live page; on the other hand, it's best on SO for questions to be self-contained. Jon Skeet has posted other guidelines on asking the perfect question. Also check out the SO FAQs and lurk a little.outis– outis2011-04-19 08:50:22 +00:00Commented Apr 19, 2011 at 8:50
-
thanks for that comment dude. I'll change my question for better.user692121– user6921212011-04-22 06:51:34 +00:00Commented Apr 22, 2011 at 6:51
4 Answers
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() {
//
});
});
Comments
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.
5 Comments
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.