1

I have a page in which content is brought in via ajax. The problem I am having is adding the relevant event listeners after the content has loaded. Is there a way to tell the browser to run all the scripts from the head again?

Below is a simple example of code that gets run from the head of the page, obviously any new html elements matching .RRCustomizeBox .customize brought in via AJAX will not have the following click event.

e.g.:

_vvdCMS.kklsRegions = {

    init: function (){
        $(document).ready(function(){
            
            $('.RRCustomizeBox .customize').click( function(){
                _vvdCMS.kklsRegions.showRRCustoms(this);
            });
            
        });
    },
    
    showRRCustoms: function(obj) {
        var objParent = $(obj).parent();
        objParent.find('.RRCustomizeBoxForm').fadeIn(700);
    }
}
_vvdCMS.kklsRegions.init();
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • If you're smiply binding events, you should be using event delegation, such as with jQuery's [`delegate`](http://api.jquery.com/delegate) or [`on`](http://api.jquery.com/on) methods. – zzzzBov Aug 27 '12 at 19:29

2 Answers2

5

You can put all your initialization code in a function and call that function from two places:

  1. In document.ready()
  2. After you load new content

For example:

function initDynamicEventHandlers() {
    // set up your event handlers here
}

$(document).ready(initDynamicEventHandlers);

$(whatever).load(url, initDynamicEventHandlers)

You will have to make sure that any content that is not replaced does not get multiple event handlers installed.


Or, second option, you for some types of logic (like mouse and key events), you can use delegated event handling and install the event handling once attached to a static parent object that is not replaced and the event handling will work without change for your dynamic content that changes underneath.

For that, you use the delegated form of .on():

$(static parent object selector).on('click', dynamic object selector, fn)
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Thanks.. i'm going to aim for this set up... the site is quite complex at the moment so have decided to start by placing ajax content (full pages) into separate container and apply js accordingly... once organized better I'll go from there and aim for you suggestion. Thanks. –  Aug 27 '12 at 21:50
3

This may be a late but this is what I do when I need ajax.

$(document).ready(function () {
$(document.body).on('click', '.Selector_S', function () { function_F(event, this) })
}

function function_F(event, d){
...do sth here...
}

And you dont need to reinitiate event listeners at all or write anything in ajax function.

Flood Gravemind
  • 3,773
  • 12
  • 47
  • 79