0

I tried something like the following but if the page I'm loading has javascript it's not running because the elements are created after page load. When the javascript is something I wrote I simply call the function again after load() and it's ok, but what can I do for the plugins the page has? Like contact forms etc?

Whats is the correct way doing ajax calls in wordpress so as my rest javascript wont brake? Thanks!

$('#subpage_arrows a').live("click", function(){

      $('.content_inside').wrap('<div id="ajax_content" />');
      $('#ajax_content').css('height',$('.content_inside').height());

      var toLoad = $(this).attr('href')+' .content_inside';  

      $('.content_inside').fadeOut('fast',loadContent);

      $('#load').remove();  
      $('#content').append('<div id="load">Loading...</div>');  
      $('#load').fadeIn(900);  
      window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-5);  
      function loadContent() {  
          $('#ajax_content').load(toLoad,'',showNewContent());
      }  
      function showNewContent() {  
          $('#ajax_content').hide().fadeIn(1000,hideLoader()).css('height','auto');

      }     
      function hideLoader() {  
          $('#load').fadeOut('normal');
      }  
      return false;     

});

1 Answer 1

1

Short answer: it's not possible what you're asking, in the right way.

Because the DOM is changed, the elements that were removed had their events attached on them removed also, so you need to run that javascript again on the new elements. And if you have no control over those plugins and their javascript, then you'll have to do this the ugly way. This means that you need to search for <script> tags inside the ajax response and inject them in the document.

What's even worse, you will need to bypass browser "security" measures by carefully passing strings like '<scr' + 'ipt>' to $.append() (or whatever innerhtml wrapper you use). Also avoid executing any javascript code that contains document.write calls (here's why).

As a side note, try to avoid $.live in favor of $.delegate:

$('#subpage_arrows a').live("click", ... => $('#subpage_arrows').delegate("a", "click", ...

(you narrow down the dom selection)

2
  • 1
    And as of jQuery 1.7, delegate() has been superseded by the on() method.
    – Geert
    Commented Nov 16, 2011 at 14:15
  • true. So then I guess click < delegate < on Commented Nov 16, 2011 at 20:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.