Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 887
Samuel Fullman Avatar asked May 17 '13 04:05

Samuel Fullman


People also ask

How replace HTML with another HTML in jQuery?

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.

Can jQuery replace JavaScript?

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.

Which method is used to replace with the keyword jQuery?

jQuery replaceWith() Method The replaceWith() method replaces selected elements with new content.

Why is jQuery used to wire up events?

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.


2 Answers

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({})
like image 189
Arun P Johny Avatar answered Sep 22 '22 11:09

Arun P Johny


You could use Event Delegation, so you don't have to re-bind.

like image 23
mar10 Avatar answered Sep 20 '22 11:09

mar10