a duck
a duck

Reputation: 69

jQuery doesn't like .on and .append?

I have a weird problem. I'm currently working on loading posts using PHP, AJAX and MySQL. The code structure itself looks like this:

My code structure

--- main.js ---

$(window).load(function(){
     initAjax();
});

--- ajax.js ---

function initAjax(){

//   Toggles a navigation

     $(document).on('click', '.btn.open', function(){
         ... toggles a window ...
     });

//   Add new posts

     $(document).on('click', '.btn.refresh', function(){
         $.ajax({
              ... ajax stuff ...,
              success: function(html){
                   // Show new posts
                   $('.post_container').prepend(html);
              }
         });
     });
}

So what is the problem?

When I append new posts they'll show up, but I am not able to click .btn.open anymore - Shouldn't 'on()' fix this? When I go to the Google Chrome console.

Does somebody know a potential way to solve the problem?

Edit:

  1. The appended posts are the same as the default loaded posts!
  2. '.btn.open' exists (div with class="btn open")
  3. I am using jQuery v2.0.3 (so .on should work!, .live and .delegate were replaced by .on!)
  4. Removed an error message that was created by a corrupted Chrome extention = No change.
  5. Created a .gif showing the problem in action: http://d.pr/i/cJB3
  6. FIXED! @cmorrissey found a small solution by replacing $(document) with $('body')

    BUT

  7. This fix doesn't seem to be a perfect solution since $(document) normally has to work! Since I want clean code, I am totally going to try out @Potherca's Short, Self Contained, Correct, Example method and probably I'll find the solution this way. Thanks

Upvotes: 2

Views: 117

Answers (1)

cmorrissey
cmorrissey

Reputation: 8583

You need to use 'body' or document.body instead of document.

    $('body').on('click', '.btn.refresh', function(){
         $.ajax({
              ... ajax stuff ...,
              success: function(html){
                   // Show new posts
                   $('.post_container').prepend(html);
              }
         });
     });

Reason: The addition of content to the body doesn't bubble up to the document level (http://bugs.jquery.com/ticket/11621), it looks like you can also use window

Upvotes: 1

Related Questions