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.
To replace a DOM element with the specified HTML or DOM elements using jQuery, use the replaceWith() method. The replaceWith (content) method replaces all matched elements with the specified HTML or DOM elements. This returns the JQuery element that was just replaced, which has been removed from the DOM.
Since jQuery is nothing but a library of JavaScript, it cannot replace JavaScript. All jQuery code is JavaScript, but jQuery doesn't include all the JavaScript code. One thing you should understand is that they are not two programming languages; instead, they both are JavaScript.
jQuery replaceWith() Method The replaceWith() method replaces selected elements with new content.
jQuery makes it straightforward to set up event-driven responses on page elements. These events are often triggered by the end user's interaction with the page, such as when text is entered into a form element or the mouse pointer is moved.
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
Ex:
$('.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
Ex:
var ct = $('.container').html('');
ct.find('li').draggable({})
You could use Event Delegation, so you don't have to re-bind.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With