0

I'm trying to make a control panel for my user where the page is never refreshed, but the different panels that hold relevant content are "refreshed" to reflect changes. I do this by either using:

.load() OR

.html() // for reading .get() and .post() results

However, when I try to load the new content, none of the JQuery I applied to relevant loaded classes and IDs are maintained. I can kind of fix this by including the JQuery on the loaded content, but that seems.. Wasteful, and hard to maintain.

Is there any way to automatically apply existing JQuery settings to loaded content?

Daniel Brown
  • 2,942
  • 5
  • 29
  • 41
  • 1
    Look into using jquery delegates or the on function. Basically dynamically loaded elements either need the events reapplied to them OR they need some other persistent DOM element that can delegate events to them. Here is some good info: http://stackoverflow.com/questions/8359085/delegate-vs-on – David Fleeman Nov 08 '13 at 19:38
  • Thank you for the great reference! – Daniel Brown Nov 08 '13 at 19:52

1 Answers1

3

jQuery events are bound at run-time, typically in a DOM ready function, so if you have the following:

$(".test").click(function() {

You have a click event handler for all elements of class "test" that are found at runtime. Now you load in some new HTML via AJAX or some other function. Even if this new elements have the class "test", this handler wont apply, because at run time that handler didn't know about these new elements. The solution: event delegation

$(document).on("click", ".test", function() {

This above will bind a handler to the document that listens for clicks on elements with the class "test". document isn't very specific, so it's best to substitute that with the container of the new HTML being loaded.

tymeJV
  • 103,943
  • 14
  • 161
  • 157
  • Thanks for the help. For some reason, I forgot that you could attach listeners to the page. I appreciate the help, and the excellent explanation. – Daniel Brown Nov 08 '13 at 19:53