Samuel Fullman Samuel Fullman - 8 months ago 58
Javascript Question

how to replace HTML with jQuery but keep event bindings

this is more a strategic question than a specific one, but I think it's precisely asked so here goes:

let's say I have a page or ap that has 3 separate sections. A change on part of the form sends an ajax post to the server, and this requires a change in section two. I want to send back the re-processed HTML output of section 2, and have this replace the original state of section 2

but, section 2 has many elements that have change, click, drag etc. bindings - and from experience when I do a html replace, I lose all my bindings.

HOWEVER, this leaves me with rewriting certain things in many of the elements in section 2 individually so as not to lose the bindings.

I KNOW there's an easier approach to this, seems like a common problem. Can anyone provide me with the "aha" part of this question, and perhaps a few examples or links? I really appreciate it.

Answer Source

You will need to divide the problem into two sections

Handling events
This can be done using event delegation using $.on(). ie instead of registering events on the element you register on a parent which will not be removed

$('.container').on('click', 'a', function(){
    //do something

Handling widgets like draggable
Here I think you are out of luck because I don't see any other way than to reinitialize those widgets once the new dom elements are added

var ct = $('.container').html('');