Search code examples
jqueryajaxinternet-explorer-8magnific-popup

Implement event delegation from document body by default


My issue start from a problem in IE8 when loading dynamic html pages that contain script tags via ajax (using magnificPopup.js).Therefore I had to remove all the js code from these dynamically called pages and put them in a seperate .js file but then it requires using .on for every single jQuery selector as all the elements were not on the page when the new .js page was loaded with the parent page.

Q: is there a way to make every single jQuery selector

$('#myId') or $('.myClass') 

to work as follows

$('body').on('click','#myId',function(){
   /*my code ...*/
})

Solution

  • Seems like the right solution would be to call your functions in the ajax callback block.

    You'd put your behaviors in a named function, which can be loaded about anywhere:

    function myFunction() {
        $('.myClass').click(function() { ... });
    }
    

    And then call that after the new file is loaded via ajax:

    $.ajax({...})  
    .success(function() {
        myFunction();
    });